# A random number generator

Discussion in 'C++' started by Joseph, Sep 7, 2004.

1. ### JosephGuest

Hi all,

I am a newbie with a problem,I want to have a random number generator
which generate numbers satisfied normal distribution(gaussian).I found
that GNU GSL lib provids some functions which could do this ,but i still
can not control the mean value and upper/lower limit it generated.below
is the code :

===================================
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>

int main (void)
{
const gsl_rng_type * T;
gsl_rng * r;

// select random number generator
r = gsl_rng_alloc (gsl_rng_mt19937);

double sigma = 10;
for (int i = 0; i < 10; i++)
{
double v = gsl_ran_gaussian_tail(r,4.5, sigma);
}

gsl_rng_free (r);

return 0;
}
===============================

one problem is ,it does not cut off from 4.5 and generated very big
numbers,i want to control the output ,say,between 0-100 with mean 50,is
there any way could do that ?

Thanks a lot,guys!!

Joseph, Sep 7, 2004

2. ### Brooks MosesGuest

Joseph wrote:
> I am a newbie with a problem,I want to have a random number generator
> which generate numbers satisfied normal distribution(gaussian).I found
> that GNU GSL lib provids some functions which could do this ,but i still
> can not control the mean value and upper/lower limit it generated.below
> is the code :

You are asking for an impossibility; numbers which satisfy a gaussian
distribution will not fit within a fixed upper and lower limit. If you
require that the numbers fit within a fixed limit, you no longer have a
gaussian distribution.

I would suggest that you do a little bit of reading on statistical
distributions, find a distribution that fits your requirements, and then
find (or write) some code that implements that distribution. I'm fairly
sure that what you want is a Beta distribution (properly shifted and
scaled); see the url below for details, and do a Google search on "beta
distribution" to figure out how the parameters relate to the mean and
variance.

Meanwhile, from your code:
[...]
double v = gsl_ran_gaussian_tail(r,4.5, sigma);
[...]

There seems to be a reference on this function here:
http://www.lsw.uni-heidelberg.de/manuals/gsl-ref-html/gsl-ref_18.html

It states that this function returns values from the gaussian tail, with
a cut-off such that they will all be greater than 4.5. This seems to
exactly match the problem that you are complaining of.

- Brooks

--
The "bmoses-nospam" address is valid; no unmunging needed.

Brooks Moses, Sep 7, 2004

## Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.