1
votes

In my homework, I am required to depict that a method can generate an Gaussian Distribution. the matlab program is shown below:

n=100;
b=25;
len=200000;

X=rand(n,len);    
x=sum(X-0.5)*b/n;

[ps2,t2]=hist(x,50);
ps2=ps2/len;

bar(t2,ps2,'y');
hold on;

sigma_2=b^2/(12*n);
R=normrnd(0,sqrt(sigma_2),1,len);

[ps2,t2]=hist(R,50);
ps2=ps2/len;
plot(t2,ps2,'bo-','linewidth',1.5);

x is the sum of n uniformly distributed variables multiplying by b/n. And x is gaussian distributed with zero-mean and sigma^2=b^2/12n. Then I got the image where the two distribution matched. However, when I substituted the t2 inside the normal distibution density function f(x)=exp(-x.^2/(2*sigma_2))/sqrt(2*pi*sigma_2), the output is quite larger than the first one, although the shape is similar.

I wander why this occurs?

1

1 Answers

1
votes

Its because you did not normalize discrete histograms. We know that in a continuous distributions the integral of probability functions are one. For solving this issue you should divide histogram to its integral. An approximate integral of a discrete function is rectangular integral:

integral (f) = sum(f)* LengthStep 

so you should change your code this way :

n=100;
b=25;
len=200000;

X=rand(n,len);    
x=sum(X-0.5)*b/n;

[ps2,t2]=hist(x,50);
ps2=ps2/(sum(ps2)*(t2(2)-t2(1))); % normalize discrete distribution

bar(t2,ps2,'y');
hold on;

sigma_2=b^2/(12*n);
R=normrnd(0,sqrt(sigma_2),1,len);

[ps2,t2]=hist(R,50);
ps2=ps2/(sum(ps2)*(t2(2)-t2(1)));  % normalize discrete distribution
plot(t2,ps2,'bo-','linewidth',1.5);
hold on
plot(t2,exp(-t2.^2/(2*sigma_2))/sqrt(2*pi*sigma_2),'r'); %plot continuous distribution

and this is the result : enter image description here