一种生成正态随机数的方法
生成步骤
- 第一步: 产生两个(0,1)上独立的均匀分布变量u1和u2
- 第二步:考虑如下两个变量
X1=(−2loge(u1))1/2cos(2πu2) X 1 = ( − 2 log e ( u 1 ) ) 1 / 2 cos ( 2 π u 2 )
X2=(−2loge(u1))1/2sin(2πu2) X 2 = ( − 2 log e ( u 1 ) ) 1 / 2 sin ( 2 π u 2 ) - 第三步:则(X1, X2)是一对独立同分布的正态分布随机变量,都服从 N(0,1) N ( 0 , 1 ) 分布
注:理论证明请参考文献《A Note on the Generation of Random Normal Deviates》
示例代码
function x=normal(size)
%input: the size of random variables
%output:the sequence of random variable that obey normal distribution
x=zeros(1,2*size);
for i=1:size
u=unifrnd(0,1,1,2); %generate two independent random variables with uniform distribution on (0,1)
%% generate X1 and X2
X1=sqrt(-2*log(u(1)))*cos(2*pi*u(2));
X2=sqrt(-2*log(u(1)))*sin(2*pi*u(2));
x(2*i-1)=X1; x(2*i)=X2;
end
%evaluate the mean of sequence x
mean_of_x=mean(x)
%evaluate the variance of sequence x
var_of_x=var(x)
%draw histogram
hist(x,1000);
运行结果
>> x=normal(10e5);
mean_of_x =
1.0443e-04
var_of_x =
0.9999