% The Q-function by simulation
% Textbook: Part I, "Continuous Random Variable", Gaussian distribution
%
% For X ~ N(0,1), Q(x) = Pr(X > x) = 1 - Phi(x). In base MATLAB,
% Q(x) = erfc(x/sqrt(2))/2 (qfunc in the Communications Toolbox).
% For Y ~ N(mu, sigma^2), Pr(Y > y) = Q((y - mu)/sigma).

clearvars; close all
rng(0)

N = 1e6;
X = randn(1, N);

x = 0:0.25:4;
Q_theory = erfc(x/sqrt(2))/2;
Q_sim = arrayfun(@(t) mean(X > t), x);

figure
semilogy(x, Q_theory, 'r', x, Q_sim, 'o', 'LineWidth', 1.2)
xlabel('x')
ylabel('Q(x)')
legend('theory', 'simulation')
grid on
title('Small probabilities need many experiments: compare x = 4')

% Arbitrary mean and variance
mu = 3; sigma = 2; y = 6;
Y = mu + sigma*randn(1, N);
fprintf('Pr(Y > %g): theory Q(%.2f) = %.4f, simulation = %.4f\n', ...
    y, (y - mu)/sigma, erfc((y - mu)/sigma/sqrt(2))/2, mean(Y > y))
