8

I'm trying to generate a random Gaussian double in Objective-C (the same as random.nextGaussian in Java). However rand_gauss() doesn't seem to work. Anyone know a way of achieving this?

Kevin
  • 53,822
  • 15
  • 101
  • 132
Rory Harvey
  • 2,579
  • 2
  • 22
  • 27
  • Pity you didn't ask while I was at work, I looked it up and wrote one a couple months ago. – Kevin Jan 08 '12 at 18:37

1 Answers1

10

This link shows how to calculate it using the standard random() function.

I should note that you'll likely have to make the ranf() routine that converts the output of random() from [0,MAX_INT] to be from [0,1], but that shouldn't be too difficult.

From the linked article:

The polar form of the Box-Muller transformation is both faster and more robust numerically. The algorithmic description of it is: float x1, x2, w, y1, y2;

     do {
             x1 = 2.0 * ranf() - 1.0;
             x2 = 2.0 * ranf() - 1.0;
             w = x1 * x1 + x2 * x2;
     } while ( w >= 1.0 );

     w = sqrt( (-2.0 * ln( w ) ) / w );
     y1 = x1 * w;
     y2 = x2 * w;
user1118321
  • 25,567
  • 4
  • 55
  • 86
  • 1
    For `randf` use the `drand48()` function. It returns a double in the interval [0, 1). See https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/drand48.3.html – bcattle Mar 26 '14 at 21:06
  • Also use the the `log()` function to take the natural log, see http://en.cppreference.com/w/c/numeric/math/log – bcattle Mar 26 '14 at 21:21