% The bin-width trade-off: one sample, three bin counts
% Textbook: Part I, "Statistical Plots", exercise "simulation: bin-width sweep"
%
% N = 1000 samples of N(0,1), pdf histograms with k = 5, 20 and 100 bins of
% the SAME data. Few bins: wide bars, the shape is lost (bias). Many bins:
% few counts per bin, relative error 1/sqrt(n_i) is large (noise).
% Working rule: keep n_i >= 25 in the central bins.

clearvars; close all
rng(0)

N = 1000;
x = randn(1, N);
K = [5 20 100];
edges_range = [-4 4];

t = linspace(-4, 4, 200);
f = exp(-t.^2/2)/sqrt(2*pi);

figure
tiledlayout(1, 3)
for k = K
    edges = linspace(edges_range(1), edges_range(2), k + 1);
    counts = histcounts(x, edges);
    [~, c] = min(abs(edges(1:end-1) + diff(edges)/2));     % central bin
    n_i = counts(c);
    fprintf('k = %3d: central bin count n_i = %4d, relative error 1/sqrt(n_i) = %.3f\n', ...
        k, n_i, 1/sqrt(n_i))

    nexttile
    histogram(x, edges, 'Normalization', 'pdf')
    hold on
    plot(t, f, 'r', 'LineWidth', 1.5)
    hold off
    title(sprintf('k = %d, n_i = %d', k, n_i))
    xlabel('x')
    grid on
end
