Generating a random Gaussian double in Objective-C/C

前端 未结 1 1534
后悔当初
后悔当初 2020-12-16 04:19

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 wo

相关标签:
1条回答
  • 2020-12-16 04:57

    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;
    
    0 讨论(0)
提交回复
热议问题