mardi 7 septembre 2021

c++ Gaussian RNG keeps generating same sequence

I'm trying to implement a C++ class that generates Gaussian (aka normal) random floats using an API similar to Python's Numpy random number generator:

numpy.random.normal(loc, scale)

where loc is the mean and scale is the standard deviation.

Below is my attempt.

#include <cstdio>
#include <random>
#include <ctime>


class Gaussian
{
    std::default_random_engine gen;

    public:
        Gaussian()
        {
            srand((unsigned int)time(NULL));
        }

        double get(double mean, double std)
        {
            std::normal_distribution<double> nd(mean, std);
            return nd(gen);
        }
};

The problem is that in my main() function, I generate 10 random doubles, and the sequence is always the same. I am using g++ on a Mac.

int main(int argc, char**argv)
{
    srand((unsigned int)time(NULL));

    Gaussian g;
    int N = 10;
    double mean = 50.0;
    double std = 2.0;

    for (int i = 0; i < N; i++) {
        double value = g.get(mean, std);
        printf("%f\n", value);
    }
}

// Compile: g++ main.cpp

Consistently produces over multiple invocations:

47.520528
53.224019
52.765603
48.191707
46.679143
50.151444
50.194442
49.542437
51.169795
51.069510

What is going on?




Aucun commentaire:

Enregistrer un commentaire