In trying to generate a random number between 0.0
and 1.0
, my program was generating pretty much the same 'random' number each time:
int main(){
srand(time(NULL));
double fraction = 1.0 / (RAND_MAX + 1.0);
int number = rand();
cout << "Random number: " << number * fraction << endl;
The output is always 0.698...
, without fail. (Or at least in that region.)
I decided to see what would happen if I just repeat the process again within the same block:
int main(){
srand(time(NULL));
double fraction = 1.0 / (RAND_MAX + 1.0);
int number = rand();
cout << "1st random number: " << number * fraction << endl;
int number2 = rand();
cout << "2nd random number: " << number2 * fraction << endl;
cout << "\n";
This is the output of running this second block several times:
MacBook-Air-2:Worksheet2 Olly$ ./exercise5.out
1st random number: 0.700058
2nd random number: 0.870525
MacBook-Air-2:Worksheet2 Olly$ ./exercise5.out
1st random number: 0.700066
2nd random number: 0.00206314
MacBook-Air-2:Worksheet2 Olly$ ./exercise5.out
1st random number: 0.700073
2nd random number: 0.133601
MacBook-Air-2:Worksheet2 Olly$ ./exercise5.out
1st random number: 0.700073
2nd random number: 0.133601
MacBook-Air-2:Worksheet2 Olly$ ./exercise5.out
1st random number: 0.700081
2nd random number: 0.265139
As you can see, the second one is exhibiting behaviour that appears to be random, whereas the first one is remaining pretty much the same every time.
I suspect it is something to do with how my computer is compiling the code (maybe something has not been installed properly), per this discussion: http://www.cplusplus.com/forum/beginner/5131/. The discussion linked never actually came to a conclusion as to how to avoid this cross-machine difference in compiler-side behaviour.
The question: Why does "First random number" consistently exhibit much less fluctuation than "Second random number"?