DanS
DanS

Reputation: 1797

Change parameters of random number generator

I am using the boost::random to generate random velocity values and I want to change the mean and variance in response to user input.

I am using the following:

typedef boost::mt19937 RNG;
static RNG rng();

typedef boost::normal_distribution<double> DIST;
DIST dist_east(vel_e, sigma);
DIST dist_north(vel_n, sigma);

boost::variate_generator<RNG, DIST> east(rng, dist_east);
boost::variate_generator<RNG, DIST> north(rng, dist_north);

velocity.east = east();
velocity.north = north();

My problem is that I only get one value returned from the two variate generators each time it gets called. The values change when I change vel_e, vel_n or sigma but otherwise, I get the same value returned.

I tried making the dist_east, dist_north, east and north objects static but I can't change the parameters after construction.

Is there a way of achieving what I want?

Upvotes: 3

Views: 1847

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126787

In my opinion the quickest way is just to have a normal distribution with sigma 1 and mean 0. In that way, you can get values from any normal distribution just multiplying for your new sigma and adding the mean.

y = mean + sigma * x

Upvotes: 4

Alexandre C.
Alexandre C.

Reputation: 56956

If U is a normally distributed random variable with mean 0 and variance 1, then

V = mu + sigma * U

is normally distributed with mean mu and variance sigma².

So all you need is to generate standard normal random variables (mean 0, stdev 1) and scale them properly.

Upvotes: 3

B. D
B. D

Reputation: 7823

I think you might be approaching the problem the wrong way. Instead of modifying the random number generator so that you have the mean and deviation you want, you should instead make the random generator always give you a uniform distribution. Then, make your own function that takes as input this uniform distribution, and gives as output the desired distribution.

If you want normal distributions, you can see in the Wikipedia page that it's quite easy to generate a normal distribution from a uniform one.

Edit : Here's some pseudo code (I have no idea how the boost random generator works)

generateNormalDistribution(mean, deviation)  
    X = boost::uniformGeneratorBetween0and1  
    Y = boost::uniformGeneratorBetween0and1  
    return [sqrt(-2*ln(X)) * cos(2*pi*Y)]*deviation + mean

Upvotes: 0

Related Questions