发件人:Luben
主题:C-FAQ,问题 13.20
Message-ID: <Pine.GSO.3.95.980510025115.27152A-100000@chimp>
日期:1998 年 5 月 10 日星期日 03:12:21 -0400

以下版本明确使用了正态分布密度函数的逆,以及您可以指定的均值和标准差。它并不比问题 13.20 中的版本长,而且更简单。请查看。

/* Generate random numbers with mean mean, standard deviation std_dev, */
/* with a Normal (Gaussian) distribution.                              */
/* mean is any real number, std_dev > 0 (or machine epsilon).          */
/* The formula used is the inverse of the density function of the      */
/* Normal distribution:                                                */
/* x = mean +/- std_dev * sqrt((-2.0) * log(y)), 0 < y <= 1            */
/* The client should call srand(int) to initialize the seed,           */
/* before any calls to gauss_rand().                                   */
/* L.T., May 3, 1998, University of Toronto                            */

#include <math.h>
#include <float.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

double gauss_rand(double mean, double std_dev)
{
  double   y;
  unsigned bin;

  errno = 0;

  /* std_dev must be greater than 0.0 (or machine epsilon) */
  if ( ! (std_dev > DBL_EPSILON)) {
    errno = EDOM;                      /* domain error */
    perror("gaussrand: std_dev too small or zero");
    return mean;
  }

  y = (double) rand() / (RAND_MAX + 1.0);   /* 0.0 <= y < 1.0 */
  bin  = (y < 0.5) ? 0 : 1;
  y = fabs(y - 1.0);                        /* 0.0 < y <= 1.0 */
  y = std_dev * sqrt((-2.0) * log(y));

  return bin ? (mean + y) : (mean - y);
}