% Central limit theorem: a sum of many +-1 variables
% Textbook: Part I, "Continuous Random Variable", Gaussian distribution
%
% Y = X_1 + ... + X_n, with independent X_i = +-1 equally likely,
% E[X_i] = 0 and Var[X_i] = 1. Then E[Y] = 0, Var[Y] = n, and for large n
% the histogram of Y is close to the N(0, n) density.

clearvars; close all
rng(0)

n = 50;     % number of variables in the sum
N = 1e5;    % number of experiments

X = 2*randi(2, [n N]) - 3;      % +-1 values
Y = sum(X, 1);

figure
histogram(Y, -n-1:2:n+1, 'Normalization', 'pdf')   % Y takes every second integer
hold on
y = linspace(-4*sqrt(n), 4*sqrt(n), 200);
plot(y, exp(-y.^2/(2*n))/sqrt(2*pi*n), 'r', 'LineWidth', 1.5)
hold off
xlabel('y')
ylabel('f_Y(y)')
legend('simulation', 'N(0, n)')
grid on

fprintf('E[Y]:   theory = 0,  simulation = %.3f\n', mean(Y))
fprintf('Var[Y]: theory = %d, simulation = %.3f\n', n, var(Y))
