Sign in to follow this  

gaussian random numbers in C++

This topic is 4203 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hey Im looking for a random gaussian number generator (normal curve). I find it hard to believe that there isnt one in any of the C or C++ standard libraries but I havnt been able to find it. anyone know where I can find a simple one?

Share this post


Link to post
Share on other sites
you can get more or less gaussian distribution by making multiple calls to a non-gaussian random generator and averaging the results:

i.e. something like this:


int getGaussianRand(int lo, int hi)
{
if ( lo < hi )
{
int range = hi - lo;
int val = (rand() % range + lo);
val += (rand() % range + lo);
val += (rand() % range + lo);
val += (rand() % range + lo);

float fVal = (float)val * 0.25f;
return (int) fVal;
}
else
{
return 0;
}
}







remember to call srand somewhere one time with something like srand(timeGetTime());

it's probably not true gaussian distribution because in order for it to work you need each call to be random in the range supplied. some RNGs are random over time but sequential calls have poor randomness/distribution. Don't know where rand falls on this issue. but the above method has worked fine for my purposes (terrain generation)

-me

Share this post


Link to post
Share on other sites
Something like this...
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>

const double PI = 3.1415926535897;

double random01()
{
return std::rand() / double(RAND_MAX);
}

double gaussrand(double mean, double stddev)
{
return std::sqrt(-2 * log(random01())) * std::cos(2 * PI * random01()) * stddev + mean;
}

// For testing...
int main()
{
std::srand(std::time(0));
int x = 0;
for (int i = 0; i < 1000000; ++i)
{
double t = gaussrand(50, 10);
if (t >= 40 && t <= 60) ++x;
}
std::cout << (x / 1000000.0) << std::endl;
}



This produces values around 0.682613, as I would expect.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Google the Box-Muller transformation. You can implement it using the standard c rand to obtain the uniform distribution, then applying the transformation to obtain samples from a normal distribution.

Share this post


Link to post
Share on other sites

This topic is 4203 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this