%exercise (2a), ex sheet 2

N = 1000;
Delta_t = 1/N; %time step
%max = 100; %no. of basis functions
M = 1000; %no. of samples
x = zeros(M,N+1); %x(m,n+1) is the mth trajectory at time Delta_t*n
xi = randn(M,N+1); % iid gaussian rv's
T = 0:Delta_t:1; %time

for n=1:N
    for m=1:M
        x(m,n+1) = x(m,n)*(1-Delta_t/(1-(n-1)*Delta_t)) + sqrt(Delta_t)*xi(m,n);
    end;
end;

Y = x(1:M,N+1);
%estimate probabilities
eps1 = 0.01;
eps2 = 0.001;
P1 = sum(abs(Y)<=eps1)/M;
P2 = sum(abs(Y)<=eps2)/M;

%Plot a trajectory

figure;
plot(T,x(1,1:(N+1)));

%Plot Histogram
pos = -0.1:0.02:0.1;
figure;
hist(Y,pos);
h = findobj(gca,'Type','patch');
set(h,'FaceColor','r','EdgeColor','w')
xlabel('Y_N')
%ylabel('')
title(['P1 = ' num2str(P1) ', P2 = ' num2str(P2)])

%figure;
%plot(T,x(1,1:(N+1)).^2);
%hold on;
%plot(T, T-T.^2,'r');
%plot(T,Variance,'-s') 
%hold off;