0

I created this method for generating random numbers in c++ , when I call it in loop, I always get the same random value, what is wrong? Because I expect different value after every loop iteration. I am compiling it with flag -std=c++11.

float CDevice::gaussNoise(float mean, float stddev)
{
    std::default_random_engine generator(time(NULL));
    std::normal_distribution<float> distribution(mean, stddev);
    return distribution(generator);
}

main looks like this:

int main
{
    class CDevice *device;
    device = new CDevice();
    std::vector<float> vec;
    for(uint32_t i = 0; i< 10; ++i)
        vec.push_back(device->gaussNoise(1,5));
    for(uint32_t i = 0; i < vec.size(); ++i)
            std::cout << vec[i] << std::endl;
}

and output is (for example):

3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
  • 8
    Seen this so many times here... initialize your random number generate *outside* of your loop! Generally *once* at the beginning of your application. – crashmstr Jul 28 '15 at 19:29
  • Topic -> 'reffer' about random number http://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range – Charleston Anjos Jul 28 '15 at 19:30
  • You keep asking a new, identically-configured RNG, for its first output when you want to keep asking the same RNG for its successive outputs. – David Schwartz Jul 28 '15 at 19:39
  • I has to be a dupe of something. Googling "C++ random number are not changing" provides a bazillion (but fortunately not a googleplex) links. – user4581301 Jul 28 '15 at 19:44

1 Answers1

8

You reseed the random number generator with every call. Because you are calling the function continuously, time(NULL) likely doesn't change. You should seed once at the start of your program, probably in the constructor of CDevice.

yizzlez
  • 8,757
  • 4
  • 29
  • 44