0

How can my program generate different random numbers each execution?

I'm trying to do the following program

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 100);

    //Matrix 8x4 size declaration
    int16_t **mtr = new int16_t*[8];
    for (size_t i = 0; i < 8; i++) {
        mtr[i] = new int16_t[4];
        for (size_t j = 0; j < 4; j++)
            mtr[i][j] = dis(gen);
    }
    //... more code
}

All works fine, BUT each time I execute this program, the generated numbers are the same. I tried with the <ctime> library and it worked (I know It is unsecure...)

Note: With execution I mean each time I call the executable file

  • 1
    What implementation of the standard library are you using? What OS/IDE/Compiler if you don't know? – JohnFilleau Mar 18 '20 at 04:25
  • 2
    does this answer your question: https://stackoverflow.com/questions/18880654/why-do-i-get-the-same-sequence-for-every-run-with-stdrandom-device-with-mingw – M.M Mar 18 '20 at 04:27

1 Answers1

2

https://en.cppreference.com/w/cpp/numeric/random/random_device

std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.

So, apparently your implementation of std::random_device is pseudo-random. Pass something better then instead of rd() here if you can:

std::mt19937 gen(rd());
Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
  • Depending on their implementation they can create a `random_device` with a string signifying the source they want to use. Awaiting a comment from the OP to see what token string would be appropriate. (your answer looks almost exactly like my draft answer, btw :D) – JohnFilleau Mar 18 '20 at 04:27