how to generate gaussian pseudo random numbers in c for a given mean and variance?

两盒软妹~` 提交于 2019-12-10 13:18:09

问题


I have a code here which generates random numbers having a mean 0f 1 and std deviation of 0.5. but how do i modify this code so that i can denerate gaussian random numbers of any given mean and variance?

#include <stdlib.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

double drand()   /* uniform distribution, (0..1] */
{
  return (rand()+1.0)/(RAND_MAX+1.0);
}

double random_normal() 
 /* normal distribution, centered on 0, std dev 1 */
{
  return sqrt(-2*log(drand())) * cos(2*M_PI*drand());
}

int main()
{

  int i;
  double rands[1000];
  for (i=0; i<1000; i++)
  rands[i] = 1.0 + 0.5*random_normal();
  return 0;

}

回答1:


I have a code here which generates random numbers having a mean 0f 1 and std deviation of 0.5. but how do i modify this code so that i can denerate gaussian random numbers of any given mean and variance?

If x is a random variable from a Gaussian distribution with mean μ and standard deviation σ, then αx+β will have mean αμ+β and standard deviation |α|σ.

In fact, the code you posted already does this transformation. It starts with a random variable with mean 0 and standard deviation 1 (obtained from the function random_normal, which implements the Box–Muller transform), and then transforms it to a random variable with mean 1 and standard deviation 0.5 (in the rands array) via multiplication and addition:

double random_normal();  /* normal distribution, centered on 0, std dev 1 */

rands[i] = 1.0 + 0.5*random_normal();



回答2:


There are several ways to do this- all of which basically involve transforming/mapping your uniformly distributed values to a normal/gaussian distribution. A Ziggurat transformation is probably your best bet.

One thing to keep in mind- the quality of your end distribution is only as good as your RNG, so be sure to use a quality random number generator (e.g.- Mersenne twister) if the quality of the generated values is important.



来源:https://stackoverflow.com/questions/7034930/how-to-generate-gaussian-pseudo-random-numbers-in-c-for-a-given-mean-and-varianc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!