Why are my 'randomly' generated numbers ar

2019-08-23 06:06发布

问题:

I'm trying to get randomly generated numbers by using srand() and rand() but with no avale: every time I run the program it increases by a certain amount of numbers. But if I use a for statement, no pattern can be seen.

For example, if I use the code provided below and run and close the program 10 times, the output will be:

42
52
72
78
85
92
12 (it has reset)
32
48  

Note: one strange thing I noticed about this that when I unfocus or minimize Visual Studio and close the Command Prompt, the next time I run the program the number increases by more than 20, but, if I don't unfocus or minimze Visual Studio the number increases by just little over 1-5. Why's that?

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand (time(NULL));

    int random_number = rand () % 100 + 1;
    cout << "Random number: " << random_number << endl;

    return 0;
}

But, if I use this code:

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand (time(NULL));

    for (int i = 0; i < 10; i++) {
        int random_number = rand () % 100 + 1;
        cout << "Random number: " << random_number << endl;
    }

    return  0;
}

the numbers don't have a clear pattern and I get the output:

31
10
81
66
74
14
6
97
39
23 

They increase and decrease randomly by random amounts. What seems to be the problem here?

回答1:

The first few random numbers returned by some versions of rand (looking at you Microsoft) are highly correlated to the seed they start with, just due to the random number generator formula being used. Since the time isn't changing much between runs, neither do the random numbers. If you throw away the first few random numbers that get returned you can get much better results.

A better solution is to use std::uniform_int_distribution instead of rand.



回答2:

Another potential issue is some implementations of rand may interact poorly with certain modulos. For that reason you may want to consider something like this instead:

 int v = ((double)rand() / (double)RAND_MAX) * 100 + 1;

Still not ideal, but easy.



标签: c++ random