# 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.

## 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 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 on other sites
I need something with a fixed average and stdev tho (like 0,1 normally) so I can modify it predictably.

##### Share on other sites
I'd give Boost a go. Try this: Getting Started with Boost. Took me about 15 minutes to compile the Boost libraries and set up Visual Studio to use them first time I used it.

##### Share on other sites
Yeah there definitely isn't one in the C++ standard libraries. So you'll either have to write your own or use an external library.

-me

ok cool, thanks

##### 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 on other sites
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 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.