6

Possible Duplicate:
Generating a random Gaussian double in Objective-C/C

Is there any way of getting a random number not from a uniform distribution, but from a Gaussian (Normal, Bell Curve) distribution in iOS? All the random number generators I have found are basically uniform and I want to make the numbers cluster around a certain point. Thanks!

Community
  • 1
  • 1
syzygy
  • 1,356
  • 3
  • 16
  • 28
  • possible duplicate of [Generating a random Gaussian double in Objective-C/C](http://stackoverflow.com/questions/8779843/generating-a-random-gaussian-double-in-objective-c-c) and http://stackoverflow.com/questions/7034930/how-to-generate-gaussian-pseudo-random-numbers-in-c-for-a-given-mean-and-varianc and http://stackoverflow.com/questions/75677/converting-a-uniform-distribution-to-a-normal-distribution – finnw Oct 18 '12 at 13:44

2 Answers2

9

Just use a uniform distribution generator and apply the Box-Muller Transform:

double u1 = (double)arc4random() / UINT32_MAX; // uniform distribution
double u2 = (double)arc4random() / UINT32_MAX; // uniform distribution
double f1 = sqrt(-2 * log(u1));
double f2 = 2 * M_PI * u2;
double g1 = f1 * cos(f2); // gaussian distribution
double g2 = f1 * sin(f2); // gaussian distribution
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Perfect, I didn't know about this transform. Many thanks! – syzygy Oct 18 '12 at 07:05
  • See also [Wikipedia](http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform) for the “polar” version of this, which avoids the trig functions but may require more calls to the uniform generator. – rob mayoff Oct 18 '12 at 07:28
  • Polar form for Objective-C is also [here](http://stackoverflow.com/a/8779877/1431728). – JohnK Jun 18 '13 at 15:04
  • @robmayoff Thanks, but isn't `log( u1 )` `-infinite` when `arc4random` returns `0` ? – Satachito Aug 09 '18 at 08:55
  • The probability of generating ±∞ is about 1/(2^32 - 1) ≈ 2.32831*10^-10. (I say “about” because when `f1` is -∞, there is a 1/UINT32_MAX probability that `g2` is NaN.) The min/max finite values for `g1` and `g2` are sqrt(2*log(1/UINT32_MAX)) ≈ ±6.66044. The total probability outside of those finite extrema is erfc(sqrt(log(2^32 - 1))) ≈ 2.73015*10^-11. So there is a larger than proper probability of generating ±∞. – rob mayoff Aug 09 '18 at 15:06
1

One simple option is to add several numbers from a uniform distribution together. Many dice based games use this approach to generate roughly normal distributions of results.

Distribution of rolling 3 6 sided dice

via wikipedia

If you can be more specific about what distribution you want there may be more precise solutions but combining several rolls is an easy and fairly flexible solution.

Jonah
  • 17,918
  • 1
  • 43
  • 70