c++ - Will rand() sometimes return the same consecutively? -
i'm curious, can single-threaded program ever same return value 2 consecutive calls rand()
?
so, assertion ever fire?
assert(rand() != rand());
if can find 1 example does, answer question "yes".
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { unsigned int i; for(i = 0; ; i++) { int r = rand(); if (r == rand()) { printf("oops. rand() = %d; = %d\n", r, i); break; } } return 0; }
prints oops. rand() = 3482; = 32187
on windows visual studio 2010.
edit: use version below detect sequences 2 consecutive rand() calls return same value. c specifies rand() should return "pseudo-random integers in range 0 rand_max" , rand_max should @ least 32767. there no constraints on quality of prng, or it's implementation, or other details such whether 2 consecutive rand() calls can return same value.
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { unsigned int i; int r1 = rand(); int r2 = rand(); for(i = 0; ; i++) { if (r1 == r2) { printf("oops. rand() = %d; = %d\n", r1, i); } r1 = r2; r2 = rand(); } return 0; }
Comments
Post a Comment