mardi 28 juillet 2015

C++ random number are not changing

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

Aucun commentaire:

Enregistrer un commentaire