Random number generating...

Started by
23 comments, last by IronMan9675 22 years, 8 months ago
Wouldn''t

(rand() / RAND_MAX) * 5.0;

produce more evenly distributed random numbers between 0 and 5, than rand() % 6?
Advertisement
srand(time());uint rnum = rand();uint rnum2 = rnum;for (int i=0;i srand(rnum); rnum *= rand() / max;} 


Would that work very well?
(http://www.ironfroggy.com/)(http://www.ironfroggy.com/pinch)
quote:
Wouldn't
(rand() / RAND_MAX) * 5.0;
produce more evenly distributed random numbers between 0 and 5

Actually, that code produces a zero-mean process with zero entropy.

Edited by - Stoffel on August 14, 2001 5:55:58 PM
its funny how u guys turn a simple random number generator into a complex algorithm

Don''t use modulus (rand() % n) for random numbers. Some random number generators have problems for certain values of n. For instance, on my decstation rand() % 2 actually alternates 0 and 1, regardless of what you seed the random number generator with!

These kind of artifacts are actually fairly common. Use it was it was intended, by multiplying and rounding up or down.
I use Shawn Cokus''s implementation of the Mersenne Twister in my GBA Lib I''m writing. There''s also Left Shift Register Combiners which produce randomish (sequence over 2^32 depending on start sequence) numbers even quicker. LSRC are usually covered in Cryptography. I haven''t looked at the Random Numbers in NR yet.

Stay Lucky, Graham "Mournblade" Reeds,
ICQ: 30514803
http://homepage.dtn.ntl.com/grahamr/
Stay Lucky, Graham "Mournblade" Reeds,ICQ: 30514803http://homepage.dtn.ntl.com/grahamr/
quote:Original post by ironfroggy
srand(time());uint rnum = rand();uint rnum2 = rnum;for (int i=0;i<rnum2;i++) { srand(rnum); rnum *= rand() / max;}  


Would that work very well?

No, that would not work very well at all. I don''t really see what you''re doing, but doing repeated actions such as multiplication reduce the ''randomness'', and calling srand more than once in the same program is simply a bad idea unless you know exactly what you''re doing. (In this case, it''s almost entirely pointless.)

I used the RAND_MAX solution long before I heard of the standard modulus solution. All you have to do is the following:

(float)rand() * (float)((float)MAX/(float)RAND_MAX);

And you can precompute the conversion factor (float)((float)MAX/(float)RAND_MAX) so that each number you generate requires only a multiplication, instead of a modulus division, which, I think (but am not entirely sure) is faster.
quote:
a zero-mean process with zero entropy.


Strike three! I''m out! Didn''t understand a word of that sentence above.

Why wouldn''t the (rand() / RAND_MAX) * anything work?

- The "original" anonymous poster.

quote:
a zero-mean process with zero entropy.


Strike three! I''m out! Didn''t understand a word of that sentence above.

Why wouldn''t the (rand() / RAND_MAX) * anything work?

This topic is closed to new replies.

Advertisement