如何在C中获得足够好的伪随机均匀分布整数进行统计模拟? [英] How to get pseudo-random uniformly distributed integers in C good enough for statistical simulation?
问题描述
我正在编写蒙特卡罗模拟,并且需要大量随机位来生成均匀分布在 {1,2,...,N} 上的整数,其中 N<40.使用 C rand
函数的问题在于,使用标准的 rand % N
技术我会浪费很多非常好的位.生成整数的更好方法是什么?
I'm writing a Monte Carlo simulation and am going to need a lot of random bits for generating integers uniformly distributed over {1,2,...,N} where N<40. The problem with using the C rand
function is that I'd waste a lot of perfectly good bits using the standard rand % N
technique. What's a better way for generating the integers?
我不需要加密安全的随机数,但我不希望它们歪曲我的结果.另外,我不考虑从 random.org 下载一批解决方案.
I don't need cryptographically secure random numbers, but I don't want them to skew my results. Also, I don't consider downloading a batch of bits from random.org a solution.
推荐答案
rand % N
不起作用;除非 RAND_MAX + 1
是 N
的倍数,否则它会扭曲你的结果.
rand % N
does not work; it skews your results unless RAND_MAX + 1
is a multiple of N
.
正确的做法是找出小于RAND_MAX
的N
的最大倍数,然后生成随机数,直到小于该值.只有这样你才应该做模运算.这为您提供了 50% 的最坏情况拒绝率.
A correct approach is to figure out the largest multiple of N
that's smaller than RAND_MAX
, and then generate random numbers until it's less than that value. Only then should you do the modulo operation. This gives you a worst-case rejection ratio of 50%.
这篇关于如何在C中获得足够好的伪随机均匀分布整数进行统计模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!