% Central Limit Theorem Demos
clear all
close all

  disp('Demos of CLT')
  lw = 2; 
  set(0, 'DefaultAxesFontSize', 16);
  fs = 15;
  msize = 10;
  
figure(1)
subplot(3,2,1)
hist(exprnd(1, [1, 10000]),40) %histogram of 10000 exponential
subplot(3,2,2)
hist(mean(exprnd(1, [2, 10000])),40) %histogtam of 10000
%averages of 2 exponential
subplot(3,2,3)
hist(mean(exprnd(1, [3,10000])),40) %histogtam of 10000
%averages of 3 exponential
subplot(3,2,4)
hist(mean(exprnd(1, [5, 10000])),40) %histogtam of 10000
%averages of 5 exponential
subplot(3,2,5)
hist(mean(exprnd(1,[10, 10000])),40) %histogtam of 10000
%averages of 10 exponential
subplot(3,2,6)
hist(mean(exprnd(1, [100, 10000])),40)%histogtam of 10000
%averages of 100 exponential

%%
% Central Limit Theorem -- Uniforms
disp('Demo of CLT by Simulation: Uniforms')
figure(2)
subplot(3,2,1)
hist(rand(1, 10000),40)
subplot(3,2,2)
hist(mean(rand(2, 10000)),40)
subplot(3,2,3)
hist(mean(rand(3, 10000)),40)
subplot(3,2,4)
hist(mean(rand(5, 10000)),40)
subplot(3,2,5)
hist(mean(rand(10, 10000)),40)
subplot(3,2,6)
hist(mean(rand(100, 10000)),40)
% print -depsc 'clt0.eps'


%%
%=================================
% SUM OF 20 UNIFORMS on [0, 1]
close all
randn('state',1)
apn1 =[];
nn = 20;
for i = 1:30000
apn1=[apn1 sum(unifrnd(0,1,nn,1))];
end
figure(4)
 plot(4:0.01:16, normpdf(4:0.01:16, 10, sqrt(20/12)),'g-','linewidth',4)
 hold on
 histo(apn1, 50, 1, 1)
 axis tight
 hold off
 %%
 %-------------
 % AVERAGE SCORE IN 20 ROLLS OF A FAIR DIE or SINGLE ROLL OF
 % 20 FAIR DICE
 apn2 =[]; %keep the mean score here
for i = 1:10000  % repeat 30000 times rolling of 20 dice
apn2 = [apn2 mean(unidrnd(6, 1, 200))]; % add the ave score in 
% the current run
end
figure(5)
 hist(apn2, 40)
 
 
 %% CLT AGAIN
  set(0, 'DefaultAxesFontSize', 12);
  
 close all
beta = 3; %the mean of exponentials
                % f(x) = 1/beta * e^(- x/beta)
ee = exprnd(beta, 500000,1); %generate 1/2 million of those
figure(6)
subplot(1,4,1)
hist(ee,100) %show histogram, looks like exponential, of course
subplot(1,4,2)
normplot(ee)
for i = 1:10000
     ees(i) = sum( ee((i-1)*50+1:i*50) ); %sum the chunks of 50
end
subplot(1,4,3)
eess = (ees - 50*beta)/(sqrt(50)*beta); %the mean is n * beta
%and the variance is n*beta^2, i.e., std=sqrt(n)*beta
hist(eess, 80)
subplot(1,4,4)
normplot(eess)




