function simulate_bernoulli_trials(N, M, p)
rng('default'); % Reset the random number generator
trials = rand(N, M) < p; % Generate N x M matrix for Bernoulli trials
sums = sum(trials, 1); % Sum each column to get k of each experiment
edges = -0.5:1:(N + 0.5); % Define histogram edges
h = histogram(sums, edges); % Get histogram of sums
title('Histogram of successes in Bernoulli trials');
xlabel('Number of successes (k)');
ylabel('Number of experiments');
estimatedProbabilities = h.Values / M; % Calculate estimated probabilities P(k)
disp(estimatedProbabilities); % Display without using ';' to avoid suppressing the output
theoreticalPk = bino_pk(N, p); % Calculate theoretical P(k)s
disp(theoreticalPk); % Display theoretical probabilities
averageError = mean(abs(estimatedProbabilities - theoreticalPk)); % Calculate average absolute error
disp(averageError); % Display the average error
figure; % Create a new figure
bar(0:N, [estimatedProbabilities; theoreticalPk]'); % Plot both estimated and theoretical P(k)s
title('Comparison of estimated and theoretical probabilities');
xlabel('Number of successes (k)');
ylabel('Probability');
legend('Estimated P(k)', 'Theoretical P(k)');
set(gca, 'xticklabel', 0:N); % Set correct values for x axis labels
end
bino_pk.m
function Pk = bino_pk(n, p)
k = 0:n; % Range of successes
Pk = arrayfun(@(x) nchoosek(n, x) * p^x * (1-p)^(n-x), k); % Calculate P(k)
end
The past few labs have been plagued with a strange issue, that when i export as pdf the black text turns white, and I’m guessing my explanation for the last few where missed, so I’m requesting that who ever is reading this right now, please go back and see what i wrote. (I don’t want to lose marks lol)