简体   繁体   English

使用rand()在C语言中生成不相关的数字

[英]generate uncorrelated number in the C language using rand()

I want to generate uncorrelated random number to do a simulation... However, the numbers generated by the rand() function in the C language are correlated. 我想生成不相关的随机数来进行模拟......但是, C languagerand()函数生成的数字是相关的。
Is there any possibility to use the rand() function and generate multiple random streams? 有没有可能使用rand()函数并生成多个随机流?
I mean, if the rand() function generate for me a series of correlated numbers, can I cut this series into different streams. 我的意思是,如果rand()函数为我生成一系列相关数字,我可以将这个系列剪切成不同的流。 Then use these streams independently? 然后独立使用这些流?

Thanks 谢谢

You are indeed correct. 你确实是对的。 They are normally autocorrelated as the normal generator implementation is linear congruential (although the C standard does not mandate this). 它们通常是自相关的,因为正常的生成器实现是线性同余的 (尽管C标准没有强制要求)。 As such an xy plot of successive numbers will fail a chi square test for random 2D dispersion. 因此,连续数字的xy图将无法进行随机2D色散的卡方检验。

Depending on your application, you could look at Bays-Durham shuffle which, to my knowledge, passes the diehard test for randomness: it's aim is to defeat autocorrelation effects. 根据你的应用,你可以看看Bays-Durham shuffle,据我所知,它通过了随机性的死硬测试:它的目的是打败自相关效应。

I direct you to www.nr.com for an implementation and the rand1 , rand2 functions in particular. 我将您引导至www.nr.com进行实施,特别是rand1rand2功能。 A more modern way is to use a mersenne twister scheme but a little tricker to implement (by the way C++11 has this generator as part of its standard library). 更现代的方法是使用mersenne twister方案,但实现一点点试图(顺便说一句,C ++ 11将此生成器作为其标准库的一部分)。

If your C implementation has rand_r , you can try that. 如果你的C实现有rand_r ,你可以试试。 It lets you specify a location to store the state. 它允许您指定存储状态的位置。

Or just use your own pseudo-random number generator. 或者只使用您自己的伪随机数生成器。

您可以使用arc4random或更好的ar4random_uniform来增加生成值的随机性(实际上ar4random_uniform证明了统一分布的值)。

Generating true random numbers on a computer is impossible, you can only generate "pseudo-random" numbers ie numbers that "looks like" random. 在计算机上生成真正的随机数是不可能的,您只能生成“伪随机”数字,即“看起来像”随机的数字。

Usually one will use a ''seed'' (small sequence of bits) with enough entropy and then "expand" it thanks to a Pseudo-Random-Number-Generator . 通常会使用具有足够熵的“种子”(小比特序列)然后通过伪随机数生成器 “扩展”它。

C rand() function generates poor quality of randomness, try PRNG that have been proposed in other answers/comments. C rand()函数产生低质量的随机性,尝试在其他答案/评论中提出的PRNG。 Some examples : 一些例子

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

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