4

I don't understand what's going on here.

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

unsigned number_in_range(unsigned, unsigned, default_random_engine);

int main()
{

    time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());

    default_random_engine rng(now);

    //
    // Print out 10 random numbers
    //
    for (int i = 0; i < 10; i++)
    {
        uniform_int_distribution<int> dist(0, 100);
        cout << dist(rng) << endl;
    }

    cout << endl;

    //
    // Do the same thing, but get the numbers from `number_in_range()`
    //
    for (int i = 0; i < 10; i++)
    {
        cout << number_in_range(0, 100, rng) << endl;
    }

    return 0;
}

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine rng)
{
    uniform_int_distribution<int> dist(range_start, range_end);
    return dist(rng);
}

An example of the output of this code is:

45
21
10
3
54
18
23
72
68
27

68
68
68
68
68
68
68
68
68
68

number_in_range() works in exactly the same way as the code in my first for loop, and yet it spits out the same value over and over again. What's different about the number_in_range() version, and how can I fix it?

Michael Dorst
  • 8,210
  • 11
  • 44
  • 71

1 Answers1

14

You are copying the random engine instead of taking a reference to it. Hence, it always has the same internal state.

Try:

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine &rng)
Rémi Bonnet
  • 793
  • 5
  • 16
  • Excellent. Thank you. – Michael Dorst Feb 20 '17 at 12:17
  • As a side note, I've noticed that the first number generated is always `45`. Is that normal? Should I always take one value and throw it away when I use the `std::default_random_engine`? – Michael Dorst Feb 20 '17 at 12:19
  • @anthropomorphic This is a pure seeding-issue. Don't throw away stuff without understanding PRNGs. Check your seed-input! – sascha Feb 20 '17 at 12:40
  • 2
    @anthropomorphic [and I guess that number changes every 20-ish minutes?](http://stackoverflow.com/questions/32730906/random-generates-same-number-in-linux-but-not-in-windows/32731387#32731387) – T.C. Feb 20 '17 at 19:34
  • @T.C. Wow, it sure does. That was very enlightening, thanks. – Michael Dorst Feb 21 '17 at 01:16