It seems like lots of people around here have problems with random numbers. I thought this might help understand the beast. It helped me.
I used this simple program to do a little study.
You give the program a text file name on the command line, and it stores the 20 random values in the text file, overwriting whatever was there. The numbers are from 1 to 6 (like a die).Code:#include <iostream> #include <stdlib.h> #include <time.h> #include <fstream> using namespace std; int main(int argc, char* argv[]) { time_t now = time(&now); srand((unsigned int)now); ofstream randout(argv[1]); int randnum; for(int x = 20;x>0;--x) { randnum = rand()%6+1; cout<<randnum<<endl; randout<<randnum<<endl; } randout.close(); system("pause"); return 0; }
I executed this ten times and came out with data like this.
You would expect, if the numbers are truly random, that as you get more and more results to get roughly the same number of all the possible values, which would give you an average value of 3.5 ((123456)/6 = 3.5). These averages range from 3.05 to 3.75. As you can see, the overall average is 3.44, which I suppose is close enough to 3.5.
That's it, this method works very well for generating random values.