问题
I have been running this code for almost ten hours with no love:
while ( true ) {
int r = rand();
assert( r != 0 );
}
I expect rand() to eventually roll a zero and thus trigger the assert.
Am I doing something wrong or does rand() never return zero?
Or have I not been waiting long enough to expect to see it? I'm on 2012-vintage 2GHz i7.
回答1:
If this link is the definition of Mac OS X rand()
, then 0 will never be produced. It's not a very good pseudo random number generator, IMHO.
Amongst its other flaws, its state is the previously returned value, which means that it is a strict function from previous value to next value; it's cycle cannot be larger than its range, which is [1, RAND_MAX-1]
. (It cannot produce 0 because 0 is a fixed-point in the algorithm.)
回答2:
The standard requires that successive calls to rand
form a sequence which is a subset of the space [0; RAND_MAX]
. It doesn't require that all the possible values occur in any of the possible sequences.
So to answer your question: You aren't guaranteed to get a zero; It's up to the implementation (And judging from the other answers, BSD libc's implementation does indeed never return 0
).
§7.22.2.2
There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits.
回答3:
Edit: what @rici said.
It looks like the FreeBSD rand never returns 0
That message chain has a patch, but it is not included in the apple open-source source.
It should eventually return zero, but on my computer, RAND_MAX
is 2147483647
printf("rand_max = %d\r\n", RAND_MAX);
Wolfram alpha can't calculate that small of a probability.
Running these examples:
prob x>0 for x binomial with n=100000 and p=.00001
prob x>0 for x binomial with n=10000 and p=.0001
prob x>0 for x binomial with n=1000 and p=.001
Show that after for a probablity of 1/N, N attempts appears to approach about 0.63
It does look like 5*N attempts should get you over 99% though.
I don't know how long your computer will take to make 10 billion calls to rand though.
来源:https://stackoverflow.com/questions/29336510/does-rand-ever-return-zero-on-osx