问题描述
我创建了一个测试应用程序,该应用程序生成10k随机数,范围从0到250000.然后我计算了MAX和min值,并注意到MAX值始终在32k左右...
I created a test application that generates 10k random numbers in a range from 0 to 250 000. Then I calculated MAX and min values and noticed that the MAX value is always around 32k...
您是否知道如何扩展可能的范围?我需要一个MAX值大约为250000的范围!
Do you have any idea how to extend the possible range? I need a range with MAX value around 250 000!
推荐答案
这是根据rand()的定义,请参见:
This is according to the definition of rand(), see:
http://cplusplus.com/reference/clibrary/cstdlib/rand/
http://cplusplus.com/reference/clibrary/cstdlib/RAND_MAX/
如果您需要更大的随机数,则可以使用外部库(例如 http://www.boost.org/doc/libs/1_49_0/doc/html/boost_random.html ),也可以自己从多个小随机数中计算出大随机数.
If you need larger random numbers, you can use an external library (for example http://www.boost.org/doc/libs/1_49_0/doc/html/boost_random.html) or calculate large random numbers out of multiple small random numbers by yourself.
但是请注意要获得的分布.如果仅对小的随机数求和,结果将不会平均分配.
But pay attention to the distribution you want to get. If you just sum up the small random numbers, the result will not be equally distributed.
如果仅将一个较小的随机数缩放一个恒定因子,则可能的值之间会存在差距.
If you just scale one small random number by a constant factor, there will be gaps between the possible values.
取随机数的乘积也不起作用.
Taking the product of random numbers also doesn't work.
可能的解决方法如下:
1) Take two random numbers a,b
2) Calculate a*(RAND_MAX+1)+b
因此,您获得的平均分布随机值最大为(RAND_MAX + 1)^ 2-1
So you get equally distributed random values up to (RAND_MAX+1)^2-1
这篇关于扩展rand()最大范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!