c++ - Why is the first result of rand() / double(RAND_MAX) is not random -


this related question - random number generation in c++ ... first number not random

#include <iostream> #include <stdlib.h> #include <time.h> using namespace std;  int main() { srand((unsigned int)time(null));  cout << rand() / double(rand_max) << endl; cout << rand() / double(rand_max) << endl; cout << rand() / double(rand_max) << endl; cout << rand() / double(rand_max) << endl; cout << rand() / double(rand_max) << endl;  return 0; } 

if run binary (.exe) on , on again, notice first result has same first 3 numbers. e.g. 0.54xxxxx every run.

no, isn't because spotting patterns there aren't any. , waiting few seconds between each run not either.

edit: 1st result has first same 3 numbers. rest "random looking". also, generator seeded srand() (on first line of code sample above).

the randomness of rand isn't specified standard. generators use seed initialize static variable, , calculate next value that, in way should "appear" random (but is, of course, deterministic). guess implementation on machine returns old value of static variable, equal seed first time through. (this sort of surprises me, it's usual return new value of static.)

anyway, it's question of quality of implementation. (i see same thing vc++11, not g++.)

edit:

just quick test see how varying seed affects first number returned:

for ( int = 1; <= 10; ++ ) {     std::srand( );     std::cout << << ": " << std::rand() << std::endl; } 

the output vc++11:

1: 41 2: 45 3: 48 4: 51 5: 54 6: 58 7: 61 8: 64 9: 68 10: 71 

with g++ 4.7.2 (cygwin version):

1: 1481765933 2: 816048218 3: 150330503 4: 1632096437 5: 966378722 6: 300661007 7: 1782426941 8: 1116709226 9: 450991511 10: 1932757444 

you seeing g++ under code blocks: can guess code blocks sets things g++ uses microsoft libraries, rather gnu ones (generally better solution).

anyway, solution simple: replace single line use seed generator with:

std::srand( std::time( null ) ); std::rand();        // throw out first value... 

and if need relatively random numbers, drop std::rand in favor of of more rigorously defined generators in c++11. (you can them boost if you're not using c++11.)


Comments