Random Numbers ...
Gregory Hicks COMFLEACTS
hicks at walker-emh.arpa
Wed Feb 24 19:00:19 AEST 1988
----BEGINNING OF FORWARDED MESSAGES----
Received: from DECWRL.DEC.COM by WALKER-EMH.ARPA ; 24 Feb 88 05:33:39 GMT
Received: by decwrl.dec.com (5.54.4/4.7.34)
id AA11545; Tue, 23 Feb 88 08:59:26 PST
Message-Id: <8802231659.AA11545 at decwrl.dec.com>
From: dantowitz%eagle1.DEC at decwrl.dec.com (David)
Date: 23 Feb 88 11:38
To: hicks at walker-emh.ARPA
Subject: Random numbers ...
In using the random number generator below the value returned by
Rand is an integer, BUT, it should be treated as the numerator of a
fraction with a divisor of 32768!!!!
So, let X = Rand ()/32768; (a floating point value)
Now 0 <= X < 1.
To get a random number from 0 to Y-1 multiply each element of the
equation by Y, which yields:
0 <= X*Y < Y.
So your random number is REALLY:
Rand() * Y
----------
32768
If you want 1 random bit DO NOT use the low bit returned by Rand!
Use the high bit!!
To get a random number of 1 bit what you are really doing is using
a value of 2 for Y, so you get:
Rand()*2
--------
32768
This is basically the high bit of Rand. The same holds if you want
2 random bits. Use the High bits.
The MOST random bits are the high bits. The low bits follow a short
loop and for most purposes are NOT sufficiently random for ANY
application.
On 32-bit systems I have seen a variation on the Rand function
below. The system I remember most recently returned the low 31 bits
that resulted from the multiply operation.
Be sure to read the documentation for the Rand function in your
library and note the range of values it returns (to be sure that
you have the correct denominator).
Remember that although the documentation says the numbers are "random",
the low-bits are NOT "random" at all.
Be careful who you trust when someone gives you a random number
generator. They tend to be passed down from "generation" to
"generation" without anyone checking the validity of the generator.
Knuth is a good source of information for this stuff.
David Dantowitz
static unsigned long int next = 1;
int rand(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed)
{
next = seed;
}
----END OF FORWARDED MESSAGES----
More information about the Comp.lang.c
mailing list