How do I get random #s?

Doug Gwyn gwyn at smoke.BRL.MIL
Fri Feb 3 09:24:20 AEST 1989


In article <19415 at dhw68k.cts.com> tsource at dhw68k.cts.com (Aryeh Friedman) writes:
>	I am new to C and I want to know how to get random numbers returned.

Unfortunately the specific details of pseudo-random number generators
in the system C libraries vary from system to system.  Usually there
is one called rand(), sometimes random().  UNIX System V has a family
*rand48().

ANSI C requires rand() to be provided, but probably your best bet for
the time being is to provide your own generator.  For example:

	static unsigned long next = 1;

	int my_rand()	/* returns range [0,32767] uniformly distributed */
	{
		next = next * 1103515245 + 12345;
		return (int)((unsigned)(next / 65536) * 32768);
	}

	void my_srand(seed)	/* sets the "seed" */
		int seed;
	{
		next = seed;
	}

This will be good enough for games, etc. but if you're doing intricate
statistical stuff (cryptosystems or Monte Carlo integration) you will
probably want to study up on RNGs; Knuth Vol. 2 is a good place to start.



More information about the Comp.lang.c mailing list