Author Topic: random function question  (Read 35731 times)

Offline thomas

  • Administrator
  • Lives here!
  • *****
  • Posts: 3979
Re: random function question
« Reply #15 on: April 05, 2006, 09:35:41 am »
Quote
Note, however, that the % method of getting random numbers is actually a fairly bad pseudo-random with most crts.
Well, it depends. The reason why people say that it produces "bad" random numbers is that it changes the distribution (unless you use a factor of the input range). For example if you have an ideal PRNG with RAND_MAX == 10000 and you write rand() % 8000, then the numbers 0 to 1999 have a 2/10000 likelihood instead of 1/10000. That is a relative difference of 100%, but neglegible as an absolute difference.
It is really bad if you need an even distribution (as said above), but in many cases this does not really matter. Often you need a random number generator just to do something that is a bit queer and does not look deterministic at first glance. For that, modulus is just good enough.

However, the good thing is that % is by order of magnitude faster than converting from int to double and back plus two double divides. True, you could replace one division by a multiply, and the compiler might eleminate the other if the output range is a compile-time constant, but the double to int conversion remains, and it is is the biggest party pooper.

Bitwise & is even better if you can live with a pow2-1 range, since it does not change the distribution (so if the input is a "good random", then the output is a "good random"), and it only takes something like 2-3 CPU cycles.

It really depends on what you do. If you need 3 random numbers, then you would probably want them to have a good distribution. If you need 300,000,000 then you would probably want them to be evaluated as fast as possible.
"We should forget about small efficiencies, say about 97% of the time: Premature quotation is the root of public humiliation."