close all;
% Problem 5: Lognormal distribution

N = 1e6;
x = linspace(-5,5,100);
dx = x(2)-x(1);

% Normal distribution X
sigma = 1;
X = sigma*randn([N 1]);
px = hist(X,x)/(N*dx); % Note the necessary normalization

subplot(211);
plot(x,px,'.'); hold on;

xc  = linspace(min(x),max(x),1e3);
pxc = 1/(sqrt(2*pi)*sigma)*exp(-xc.^2/(2*sigma^2));
plot(xc,pxc,'r');
xlim([x(1) x(end)]);
ylim([0 max(pxc)*1.1]);
xlabel('x');
ylabel('f_X(x)');
title('Normal distribution N(0,\sigma^2)');

% Lognormal distribution
y = linspace(0,10,100);
dy = y(2)-y(1);
Y = exp(X);
py = hist(Y,y)/(N*dy);

subplot(212);
plot(y,py,'.'); hold on;
yc = linspace(1e-3,max(y),1e3);
pyc = 1/(sqrt(2*pi)*sigma)*exp(-log(yc).^2/(2*sigma^2)).*1./yc;
plot(yc,pyc,'r');