% EX 1
E1=rand(2,10000);
R=sqrt(-2*log(E1(1,:)));
X=R.*cos(2*pi*E1(2,:));
Y=R.*sin(2*pi*E1(2,:));
histo(X,50,0,1)
hold on;
t=[-3:0.01:3]; 
plot(t,dnorm(t,0,1),'r')
hold off;
figure;
X1=sort(X);
stairs(X1,[1:10000]/10000)
hold on
plot(t,pnorm(t),'r')
hold off;
figure;
hold on;
plot(X,Y,'.')
hold off;
% on peut faire pareil pour Y
%%
% EX 2
U=rand(2,50000);
V=2*U-1;
S=V(1,:).^2+V(2,:).^2;
VV=V(:,S<=1);
S=S(S<=1);
n=length(S)
X=sqrt(-2*log(S)./S).*VV(1,:);
Y=sqrt(-2*log(S)./S).*VV(2,:);
histo(X,50,0,1)
hold on;
t=[-3:0.01:3]; 
plot(t,dnorm(t,0,1),'r')
hold off;
figure;
X1=sort(X);
stairs(X1,[1:n]/n)
hold on
plot(t,pnorm(t),'r')
hold off;
figure;
hold on;
plot(X,Y,'.')
hold off;
%%
% EX 3
X=randn(2,10000);
r=0;
A=[1 0 ; r sqrt(1-r^2)];
Y=A*X;
plot(Y(1,:),Y(2,:),'.')
%%
% EX 4
sig=[2 3; 3 5];
A=[2 -1; -1 1];
A*sig*A'
B=A^(-1);
Ech=randn(2,10000);
Y=B*Ech;
YY=Y(:,Y(1,:)<0.4);
sum(YY(2,:)>0.3)/10000
Z=ones(2,10000)
Z(1,:)=Y(1,:)-0.4;
Z(2,:)=Y(2,:)+2;
ZZ=Z(:,Z(1,:)<0.4);
%%
% EX 5
X2=randn(2,10000);
X4=randn(4,10000);
Y2=sum(X2.^2);
Y4=sum(X4.^2);
histo(Y2,50,0,1)
hold on;
t=[0:0.01:20]; 
plot(t,dchisq(t,2),'r')
hold off;
figure;
histo(Y4,50,0,1)
hold on;
t=[0:0.01:20]; 
plot(t,dchisq(t,4),'r')
hold off;
figure;
Y22=sort(Y2);
stairs(Y22,[1:10000]/10000)
hold on
plot(t,pchisq(t,2),'r')
hold off;
figure;
Y44=sort(Y4);
stairs(Y44,[1:10000]/10000)
hold on
plot(t,pchisq(t,4),'r')
hold off;
M2=sum(X2)/2;
M4=sum(X4)/4;
X22(1,:)=X2(1,:)-M2;
X22(2,:)=X2(2,:)-M2;
X44=ones(4,10000);
X44(1,:)=X4(1,:)-M4;
X44(2,:)=X4(2,:)-M4;
X44(3,:)=X4(3,:)-M4;
X44(4,:)=X4(4,:)-M4;
Z2=sum(X22.^2);
Z4=sum(X44.^2);
figure;
histo(Z2,50,0,1)
hold on;
t=[0:0.01:20]; 
plot(t,dchisq(t,1),'r')
hold off;
figure;
histo(Z4,50,0,1)
hold on;
t=[0:0.01:20]; 
plot(t,dchisq(t,3),'r')
hold off;