简体   繁体   中英

Need help understanding better RNG

In the last example of this post ( http://www.daniweb.com/software-development/cpp/threads/1769/c-random-numbers ), the author claims that it is a better method for producing random numbers. However, I read this line and am still confused as to what is trying to do.

random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));

I tested this code but it kept producing the value of "1" every single time.

I hope someone can provide clarification.

Say you want to generate random integer in the range [a, b) . This can be accomplished by generating random integer in the range [0, b - a) and adding a :

random_integer = a + rand(0, b - a)

We can generate random integers in the range [0, RAND_MAX] using the ordinary rand() . Now, we need to scale this interval to fit [0, r) , r = b - a . Since RAND_MAX is the maximal value returned by rand() , rand() / (MAX_RAND + 1.0) is in [0, 1) . So, r * rand() / (MAX_RAND + 1.0) is in [0, r) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM