% Sum of two fair dice: empirical vs exact distribution
% Textbook: Part I, "Two Random Variables", simulation exercise
%
% S = D1 + D2 is a function of a pair of discrete random variables. Counting
% the 36 equally likely pairs on the anti-diagonals of the 6x6 joint PDF
% table gives p_S[k] = (6 - |k - 7|)/36, k = 2..12 (a triangle).

clearvars; close all
rng(0)

N = 1e5;
S = randi(6, [1 N]) + randi(6, [1 N]);

k = 2:12;
p_emp = sum(S == k', 2)'/N;
p_exact = (6 - abs(k - 7))/36;

figure
bar(k, p_emp)
hold on
stem(k, p_exact, 'r', 'LineWidth', 1.5)
hold off
xlabel('k')
ylabel('p_S[k]')
legend('simulation', 'exact, (6-|k-7|)/36')
grid on

fprintf('E[S]:   theory = 7,     simulation = %.4f\n', mean(S))
fprintf('Var[S]: theory = %.4f, simulation = %.4f\n', 35/6, var(S))
fprintf('max |p_emp - p_exact| = %.4f\n', max(abs(p_emp - p_exact)))
