0

I'm wondering why it's advantageous to seed srand at the beginning of the program, instead of where I use it.

I generate pseudo-random numbers when seeding srand at the beginning of my program but I get the numbers all the same when I seed srand inside the function I call to generate the numbers

#include <iostream>
#include <ctime>
using namespace std;

int rng()
{
    const int SIZE = 10;
    int rng[10];
  srand(time(NULL));
    for (int i = 0; i < 10; i++)
    {
        rng[i] = rand() % 128 + 1;
        return rng[i];
    }

}

int main()
{
    int array;
  //srand(time(NULL)); If i put it here i get actual random numbers
    cout << "Welcome to the program";
    cout << "\nthis is your rng\n";
    for (int i = 0; i < 10; i++)
    {
        array = rng();
        cout << array << endl;
    }

    return 0;
}

When I run the program all of the numbers are the same, but when I delete the seeding from in the rng function and uncomment the srand in the main module the numbers are pseudo-random which is what I want. Im wondering why though. I've looked into it and heard that im seeding srand with a time and when I run that function the loop iterates so fast that all of the numbers are generated with the same seed value so they're all the same, but I'm wondering what's the difference from that and having srand(time(NULL)) in main because either way doesn't the function generate the numbers so fast they'll be at the same seed value anyway? It doesn't appear that way because of the different output but im curious, why?

1 Answers1

2

time returns number of seconds since 1.1.1970 so calling it repeatedly during one second will indeed return same values. It doesn't matter exactly where you put srand as long as it's before all rand calls and it should only be called once per program as it's global and obviously resets the random sequence. So if you use it only where you need it, you risk that when some other part of the code will need it too and calls srand again, it will interfere with your rand calls. It's not necessary to call it at all but then the seed will always be the same. It's good for debugging to have an option to set the seed deterministicly.

That said, don't use it, just don't.

As you observed time is not a good seed generator and rand is not even good random number generator, certainly not for floats and x mod n. Use <random> library. It has std::random_device which can generate true random numbers = good seeds. Sadly it's not required to. std::mt19937 is go-to RNG which together with std::XX_YY_distributions should be more than enough for everything but the most extreme need for randomness. It's also thread-safe because you control access to the generator and how it's used.

Quimby
  • 17,735
  • 4
  • 35
  • 55