本文介绍了生成随机位-C rand()中缺乏随机性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用rand()生成0或1(rand() % 2).我正在使用当前时间(srand(time(NULL)))播种.

I am using rand() to generate either 0 or 1 (rand() % 2). I am seeding it using the current time (srand(time(NULL))).

经过大量调试后,我意识到rand()绝不会连续返回16次或更多的偶数(奇数).

After much debugging, I realised that rand() never returns an even (odd) number 16 or more times in a row.

这是一个已知问题吗? C随附更好的PRNG吗?

Is this a known issue? Is there a better PRNG that comes with C?

我正在使用Visual Studio 2010在Windows 7上运行.

I am running on Windows 7 using Visual Studio 2010.

推荐答案

请尝试使用rand()>(RAND_MAX/2),而不是使用rand()%2.您只能假设rand()在间隔[0, RAND_MAX]上是统一的.

Instead of using rand()%2, try rand()>(RAND_MAX/2). You can only assume rand() to be uniform on the interval [0, RAND_MAX].

编辑:这是Shahbaz在评论中建议的,只有在发布此答案后我才注意到.

This was suggested by Shahbaz in the comments, which I only noticed after I posted this answer.

ArjunShankar在我以前的措辞中叫我:仅将rand()指定为在[0,RAND_MAX]间隔内是统一的"

ArjunShankar called me out on my previous wording: "rand() is only specified to be uniform on the interval [0, RAND_MAX]"

根据C99标准:

从技术上讲,没有指定均匀性(或 equidistributed ),而是用于实现常用PRNG(例如Mersenne Twister)的事实上的标准.这是为了允许程序员轻松创建具有非均匀分布的自定义PRNG.没有此属性,程序员将不得不从头开始实现自定义PRNG.

Technically, uniformity (or equidistributed) is not specified, but is the de-facto standard used for implementations of commonly used PRNG's (e.g. Mersenne Twister). This is to allow a programmer to easily create a custom PRNG with a non-uniform distribution. Without this property, a programmer is forced to implement a custom PRNG from scratch.

这篇关于生成随机位-C rand()中缺乏随机性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 18:43
查看更多