vendredi 28 avril 2017

How to correctly use std::normal_distribution in C++11?

I want to get random float numbers in the range [0.0,1.0], so most of these numbers should be around 0.5. Thus I came up with the following function:

static std::random_device __randomDevice;
static std::mt19937 __randomGen(__randomDevice());
static std::normal_distribution<float> __normalDistribution(0.5, 1);

// Get a normally distributed float value in the range [0,1].
inline float GetNormDistrFloat()
{
    float val = -1;
    do { val = __normalDistribution(__randomGen); } while(val < 0.0f || val > 1.0f);

    return val;
}

However, calling that function 1000 times leads to the following distribution:

0.0 - 0.25 : 240 times
0.25 - 0.5 : 262 times
0.5 - 0.75 : 248 times
0.75 - 1.0 : 250 times

I was expecting the first and last quarter of the range to show up much fewer than what is shown above. So it seems I am doing something wrong here.

Any ideas?

Aucun commentaire:

Enregistrer un commentaire