gaussian random numbers in C++

Started by
8 comments, last by GameDev.net 17 years, 10 months ago
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?
Advertisement
boost::random.
anything that doesnt involve downloading some library? Im not 100% sure how to get it working.
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
I need something with a fixed average and stdev tho (like 0,1 normally) so I can modify it predictably.
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.
My opinion is a recombination and regurgitation of the opinions of those around me. I bring nothing new to the table, and as such, can be safely ignored.[ Useful things - Firefox | GLee | Boost | DevIL ]
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
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.
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.

This topic is closed to new replies.

Advertisement