2/5 In C, the typical way to generate random numbers in the range [0, N)
is (int) ((double) rand() / ((double) RAND_MAX + 1) * N). What
guarantee is there that RAND_MAX + 1 does not overflow?
\_ RAND_MAX is 32767.
\_ RAND_MAX is guaranteed to be at LEAST 32767.
\_ aren't your parentheses misplaced wrt N?
\_ no. You generate a floating value in the range [0, 1), multiply
by N, and cast to int.
\_ right. as written, it's generating [0,1) and dividing by N,
n'est-ce pas?
\_ Note that you're casting RAND_MAX to a double. Standard IEEE754 has
54 bits of significand in a double. That's typically more than
anything a 32-bit machine has to offer. However there is no
guarantee against overflow.
By the way, rand() is a crappy generator. The method above leads to
non-uniform probability distribution (some values will be twice as
likely than the rest), etc.
\_ so can you change the seed each time, based on prev #
and other factors to make it distribute more evenly?
\_ it doesn't matter what the seed is. most implementations
of rand() just suck.
\_ understood. care to suggest a better way of
generating random numbers?
\_ digitize johnson noise and take the least
signifigant bit? i'll bet you could make
a box to do this for about a dollar in electronics.
I think there are chips that do this, or use
shot noise which is also white.
-naive physicist
\_ Actually, the best way would be to
to take some radioactive material
\_ well even just C's "random" function is better than
"rand". look at "man 3 rand". i would try the /dev
random device but then that's not very portable
and measure either the amount of
decay or the interval between two
decay events and use that as a
basis for your random numbers.
\_ read from /dev/(u)random
\_ http://www.boost.org/libs/random/index.html
\_ well even just C's "random" function is better
than "rand". look at "man 3 rand". i would try
the /dev random device but then that's not very
portable
\_ It works on MacOS X, Solaris (8+),
L1NUX, *BSD, how much more portability
do you want?
\_ (int) (drand48() * N); |