-1

I am having trouble using the random header to create a simple random number generator.

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

int main()
{

    random_device rd; //seed generator
    mt19937_64 generator{rd()}; //generator initialized with seed from rd
    uniform_int_distribution<> dist{1, 6};

    for(int i = 0; i < 15; i++)
    {

        int random = dist(generator);

        cout << random << endl;

    }

}

This code produces identical results every time I run the program. What am I doing wrong? Also is there a way to modify this code such that it will generate a floating point number between 0 and 1? I don't think the uniform_int_distribution will let me and I can't figure out which distribution to use.

EDIT: Posted a possible solution to my problem below

  • 1
    @KonaeAkira - The `` header and `srand` are disjoint – StoryTeller - Unslander Monica Apr 15 '18 at 07:19
  • 1
    You would think if there's a uniform int distribution there must be one for floats too... http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution Your problem may be platform specific. Using your code I get different numbers each time in Visual Studio 2017. – Retired Ninja Apr 15 '18 at 07:20
  • 1
    Cannot reproduce. I get different numbers every time. –  Apr 15 '18 at 07:20
  • 1
    http://www.pcg-random.org/posts/simple-portable-cpp-seed-entropy.html – Alex Reynolds Apr 15 '18 at 07:21
  • 3
    Possible duplicate of [Why do I get the same sequence for every run with std::random\_device with mingw gcc4.8.1?](https://stackoverflow.com/questions/18880654/why-do-i-get-the-same-sequence-for-every-run-with-stdrandom-device-with-mingw) – Alex Reynolds Apr 15 '18 at 07:22

1 Answers1

0

Here is what I came up with eventually:

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

int main()
{


    srand(time(0));
    default_random_engine rd(rand());
    mt19937_64 generator{rd()}; //generator initialized with seed from rd
    uniform_real_distribution<double> dist{0,1};

    for(int i = 0; i < 15; i++)
    {

        double random = dist(generator);

        cout << fixed << random << endl;

    }

}

It turns out that you actually CAN combine srand(time(0)) with an engine from the random header file, and their powers combined seem to produce random-feeling numbers better than I have managed with either alone. Please feel free to point out any problems with this arrangement.