[英]how to generate gaussian pseudo random numbers in c for a given mean and variance?
I have a code here which generates random numbers having a mean 0f 1 and std deviation of 0.5.我这里有一个代码,它生成平均为 0f 1 和标准偏差为 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;
}
I have a code here which generates random numbers having a mean 0f 1 and std deviation of 0.5.我这里有一个代码,它生成平均为 0f 1 和标准偏差为 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 |α|σ
.如果x
是来自具有均值μ
和标准偏差σ
的高斯分布的随机变量,则αx+β
将具有均值αμ+β
和标准偏差|α|σ
。
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:它从一个均值为 0、标准差为 1 的随机变量开始(从 function random_normal
获得,它实现了Box–Muller 变换),然后将其转换为一个均值为 1、标准差为 0.5 的随机变量(在rands
数组中)通过乘法和加法:
double random_normal(); /* normal distribution, centered on 0, std dev 1 */
rands[i] = 1.0 + 0.5*random_normal();
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.Ziggurat转换可能是您最好的选择。
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 (eg- Mersenne twister) if the quality of the generated values is important.需要记住的一件事 - 最终分布的质量仅与 RNG 一样好,因此如果生成值的质量很重要,请务必使用质量随机数生成器(例如 Mersenne twister)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.