close

Write a program to generate Gaussian random variables. And then use this program to calculate E[X^2]. Using the moment generation function, we can get E[X^2]=μ2+σ2, and thus E[X^2]=0+1=1.
-------------MATLAB Script-------------------------------------
% file Gaussian_RV
u=input('mean of the gaussian RV u=');
var=input('variance of the gaussian RV var=');
m=input('Number of samples m=' );
temp=0;
for k=1:m
t=0;
if t==0;
r=2;
while r>1.0
v1=2.0*rand()-1.0;
v2=2.0*rand()-1.0;
r=v1*v1+v2*v2;
end
r=sqrt((-2.0*log(r))/r);
t=v2*r;
G(k,1)=u+v1*r*var;
else
temp=t
t=0.0;
G(k,1)=u+temp*var;
end
end
G2=G.*G;
mean=sum(G2)/m;
fprintf('The mean is = %f \n', mean);
------------------------------------------------------------------------
>> gaussian_rv
mean of the gaussian RV u=0
variance of the gaussian RV var=1
Number of samples m=10000
The mean is = 0.978683
>> gaussian_rv
mean of the gaussian RV u=0
variance of the gaussian RV var=1
Number of samples m=50000
The mean is = 0.997460
>>
-------------------------------------------------------------------------
We can see that the mean calculated using program is approaching the exact value of E[X^2] as the number of samples increases.


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Irwinlin 的頭像
    Irwinlin

    變化是生活的調味料

    Irwinlin 發表在 痞客邦 留言(0) 人氣()