如何生成在C高斯伪随机数为给定的平均值和方差σ [英] how to generate gaussian pseudo random numbers in c for a given mean and variance?
问题描述
我这里有一个code产生具有平均0F 1和0.5标准偏差的随机数。但我怎么修改此code,这样我可以denerate任何给定的均值和方差的高斯随机数?
的#include<&stdlib.h中GT;
#包括LT&;&math.h中GT;
的#ifndef M_PI
#定义M_PI 3.14159265358979323846
#万一双drand()/ *均匀分布,(0..1] * /
{
回报(RAND()+ 1.0)/(RAND_MAX + 1.0);
}双random_normal()
/ *正态分布,集中于0,标准偏差1 * /
{
返回的sqrt(-2 *日志(drand()))* COS(2 * M_PI * drand());
}诠释的main()
{ INT I;
双兰特[1000];
对于(i = 0; I< 1000;我++)
兰特[I] = 1.0 + 0.5 * random_normal();
返回0;}
我这里有一个code产生具有平均0F 1个随机数
的0.5和std偏差。但我怎么修改此code,这样我可以
denerate任何给定的均值和方差的高斯随机数?
块引用>如果
X
是高斯分布,均值μ
和标准偏差σ
,那么αX+β
将有平均αμ+β
和标准偏差|α|。σ
在事实上,你已经公布的code做这种转变。它以一个随机变量,均值为0,标准差为1(从功能
random_normal
,它实现的箱穆勒变换),然后将其均值为1,标准差为0.5转变为一个随机变量(在兰特
数组)通过乘法和加法:双random_normal(); / *正态分布,集中于0,标准偏差1 * /兰特[I] = 1.0 + 0.5 * random_normal();
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; }
解决方案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 therands
array) via multiplication and addition:double random_normal(); /* normal distribution, centered on 0, std dev 1 */ rands[i] = 1.0 + 0.5*random_normal();
这篇关于如何生成在C高斯伪随机数为给定的平均值和方差σ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!