random number

Started by
9 comments, last by GameDev.net 18 years, 1 month ago
Does rand() not work well? why many people do random number algorithm? I heard of Mersenne Twister is good.
Advertisement
rand() works well enough, but it has several serious flaws. So if you need anything more than trivial generation, then its a good idea to use a better algorithm. MT is a good one, yes.

CM
Whats the limitations on rand()?
I have a book at home called Numerical Recipes in C which explains it very well and there is lots of implementations of different RNG's.

One thing I remember of hand is that it only has 16 bits of precision. When I go home tonight I'll look up the limitations and post.
Quote:Original post by Servant of the Lord
Whats the limitations on rand()?


I'm sure there are more, but the first to come to mind is that you can only use it with int's.
Quote:Original post by Servant of the Lord
Can it do bools or only only ints?


http://www.eskimo.com/~scs/c-faq.com/lib/randrange.html

(For bool, N = 2)

Quote:
No floats or doubles either?


Cast rand() to float or double and divide by RAND_MAX to get a random number from 0 to 1.
(double)rand()/RAND_MAX
Quote:Original post by Anonymous Poster
...


Thanks. I never knew this.
Well the book I referred to has a long winded explanation of why the system supplied rand() function is not terribly good, which may not be a bad thing depending on your needs.

The book does however state the if you require a random integer between 1 and 10 using the rand() function then this is how you do it

j=1+int(10.0*rand()/(RAND_MAX+1));

rather than the familiar

j=1+(rand()%10);

The reason for this is that the first uses the high order bits which, presumably are more random.

This piece of code gives you a fast floating point number between 0 and 1

This assumes your floating point is IEEE compatible
This comes from the Numerical Recipes in C++ book


unsigned long idum, itemp;
float rand;

idum = 1664525L*idum + 1013904223L;
itemp = 0x3F800000 | (0x007FFFFF & idum);
rand = (*(float *)&itemp) - 1.0;

Quote:Original post by derek7
Does rand() not work well? why many people do random number algorithm? I heard of Mersenne Twister is good.


rand() has serious flaws for serious applications. rand() is Good Enough for most game applications.

I'm not saying you should not take games seriously, I'm saying the requirements of a random number generator in most games are not as stringent as those in scientific or numeric applications where full-spread spectrum, extended repeat ranges, and low-order randomness are important considerations.

Stephen M. Webb
Professional Free Software Developer

rand() has 2 big problems:
a) you can only have 1 random number generator
b) it doesn't provide any convenience functions like random-int-in-range or some gaussian randomness.

It's easy to solve both by using boost::random or something similar.

This topic is closed to new replies.

Advertisement