Hi I've written a c++ program that uses the rand() function for random numbers and is giving me odd results. There's a lot more in the actual code but the basic idea of the code is similar to:
int main()
{
srand(time(NULL));
priority_queue<long long int> pQueueInts;
const int TRIALS = 1000000;
for (int i = 0; i < TRIALS; i++)
{
long long int holder = randomNumber();
pQueueInts.push(holder);
}
cout << pQueueInts.top();
for (int i = 0; i < TRIALS / 2; i++)
pQueueInts.pop();
cout << pQueueInts.top();
for (int i = 0; i < (TRIALS / 2) - 1; i++)
pQueueInts.pop();
cout << pQueueInts.top();
}
long long int randomNumber()
{
bool found = false;
long long int counter = 0;
while (found == false)
{
int roll = rand() % 500;
if (roll == 1)
{
roll = rand() % 500;
if (roll == 2)
found = true;
}
counter++;
}
found = false;
while (found == false)
{
int roll = rand() % 100;
if (roll == 3)
{
roll = rand() % 250;
if (roll == 4)
found = true;
}
counter++;
}
found = false;
while (found == false)
{
int roll = rand() % 530;
if (roll == 5)
{
roll = rand() % 400;
if (roll == 6)
found = true;
}
counter++;
}
return counter / 3;
}
It runs and executes fine but if I say do 1M trials and find the largest counter result from that, then I exit the program and run it again but with 1000 trials, you would expect the largest counter from that sample to be smaller than the 1M trials, yet its the exact same number. If I then change the sample to 10M I might get a new high number, turn the program off again and rerun with 1000 trials and I may get the new high number from the 10M sample as the high for 1000 sample exactly which is insanely unlikely especially with my actual code where the result has much more variance.
I assume there's something going on with the rand() function or the c++ language that I don't understand that's causing this? Thanks for any enlightenment.
Aucun commentaire:
Enregistrer un commentaire