简体   繁体   English

需要帮助来了解更好的RNG

[英]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. 在这篇文章的最后一个示例中( http://www.daniweb.com/software-development/cpp/threads/1769/c-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. 我测试了此代码,但每次都保持产生“ 1”的值。

I hope someone can provide clarification. 我希望有人可以提供澄清。

Say you want to generate random integer in the range [a, b) . 假设您要生成[a, b)范围内的随机整数。 This can be accomplished by generating random integer in the range [0, b - a) and adding a : 这可以通过生成范围为[0, b - a)随机整数并添加a

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

We can generate random integers in the range [0, RAND_MAX] using the ordinary rand() . 我们可以使用普通的rand() [0, RAND_MAX]范围内的随机整数。 Now, we need to scale this interval to fit [0, r) , r = b - a . 现在,我们需要缩放此间隔以适合[0, r)r = b - a Since RAND_MAX is the maximal value returned by rand() , rand() / (MAX_RAND + 1.0) is in [0, 1) . 由于RAND_MAXrand()返回的最大值,因此rand() / (MAX_RAND + 1.0)[0, 1) So, r * rand() / (MAX_RAND + 1.0) is in [0, r) . 因此, r * rand() / (MAX_RAND + 1.0)[0, r)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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