How do I get random #s?

Chris Torek chris at mimsy.UUCP
Fri Feb 17 02:15:17 AEST 1989


In article <1989Feb15.213335.18135 at utzoo.uucp> [love those message-IDs]
henry at utzoo.uucp (Henry Spencer) writes:
>However, as has been pointed out to me in private mail, the key issue when
>you want multiple streams of random numbers is not being able to specify
>a seed, but being able to save the state of rand() and restore it later.
>*That*, the standard rand() can't do.

Well, actually you can (as I pointed out in private mail, but I think
not coherently).  It is not suitable except as an exercise, but it goes
like this:

	struct rand_stream {
		int	rs_seed;
		unsigned long rs_calls;
	};

	struct rand_stream *rs_start(int seed) {
		struct rand_stream *rs = malloc(sizeof(*rs));

		if (rs == NULL)
			return (NULL);
		rs->rs_seed = seed;
		rs->rs_calls = 0;
	}

	int rs_rand(struct rand_stream *rs) {
		unsigned long l;

		srand(rs->rs_seed);
		for (l = 0; l < rs->rs_calls; l++)
			(void) rand();
		rs->rs_calls++;
		return (rand());
	}

Incidentally, one of the big features of `object oriented' languages
is that they encourage encapsulation of state into a data object,
eliminating on a local level global (static) variables, obviating
the need for the above sort of chicanery.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list