Random int generator being weird

Apr 28, 2015 at 12:52pm
I have a function that generates random integers and the first integer that it generates is always really small compared to the rest, and I don't understand why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
#include<random>

using namespace std;

template<typename T> T make(int min, int max);

class Rand_int {
        default_random_engine re;
        uniform_int_distribution<> dist;
public:
        Rand_int(int low, int high) :dist{ low, high } {}
        int operator()() { return dist(re); }
        void seed(int x) { re.seed(x); }
};

template<> int make<int>(int min, int max)
{
        static Rand_int r{ min, max };
        return r();
}

int main(){

        for (int i = 0; i<20; i++)
                cout << make<int>(40, 10000000) << endl;
}


Output:

118
1320017
7582516
4602580
5346343
2197288
472131
6812427
6816759
9379655
3848471
5212367
8338752
346970
536525
5315565
6735004
77291
3847604
670799
Last edited on Apr 28, 2015 at 12:52pm
Apr 28, 2015 at 2:20pm
in fact, the output should be allways the same at the moment...
You need to seed your default_random_engine, otherwise you'll allways get the same result.
std::chrono::system_clock::now().time_since_epoch().count() is the C++11 way of doing this
using srand(time(0)) and rand() are for older standards

C++11-way
1
2
3
4
5
#include <chrono>

 // ...

Rand_int(int low, int high) : re(std::chrono::system_clock::now().time_since_epoch().count()), dist{ low, high } {}


C++03-way:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <ctime>
#include <cstdlib>

 // ...

Rand_int(int low, int high) : re(rand()), dist{ low, high } {}

// ...

int main() {
    srand(time(0));
    // ...
}

Apr 28, 2015 at 2:29pm
That did the trick! Thanks!!
Topic archived. No new replies allowed.