Octave を使い始めたばかりで、次のように定義された二項確率変数の 10,000 の結果をシミュレートしようとしています。
X~Bi(5,0.2)
次の関数を使用して結果をグラフ化しました。
function x = generate_binomial_bernoulli(n,p,m)
% generate Bi(n, p) outcomes m times
x = zeros(1,m); % allocate array for m simulations
for i = 1:m % iterate over m simulations
successes = 0; % count the number of successful trials per simualtion (0-5)
for j = 1:n % iterate through the n trials
u = rand; % generate random nuumber from 0-1
if (u <= p) % if random number is <= p
successes++; % count it as a success
endif
end
x(i) = successes; % store the number of successful trials in this simulation
end
alphabet_x=[0:n]; % create an array from 0 to n
hist(x,alphabet_x); % plot graph
end
次に、関数を で呼び出しますgenerate_binomial_bernoulli(5, 0.2, 10000)
。
これは成功確率0.2の5回のベルヌーイ試行をシミュレートし、5回の試行を10,000回繰り返し、成功回数の分布をグラフ化したものです。このプロットは、シミュレーションの実験結果を示しています。
また、理論上の結果をプロットするように求められました。これは、x 軸 (0.2 * 5 = 1) で 1 回の成功を中心に正規分布したプロットであると推測されます。
- このプロットを作成して同じヒストグラムに表示するにはどうすればよいですか?
- X 軸が 0 から 5 までの範囲で、両方の軸にラベルが付けられ、凡例で色分けされた 2 つのヒストグラムでグラフを正確に表示するにはどうすればよいでしょうか?
編集
正規化された/理論上の曲線をプロットしようとした現在の関数は次のとおりです。
function x = generate_binomial_bernoulli(n,p,m)
% generate Bi(n, p) outcomes m times
emperical = zeros(1,m); % allocate array for m simulations
for i = 1:m % iterate over m simulations
successes = 0; % count the number of successful trials per simualtion (0-5)
for j = 1:n % iterate through the n trials
u = rand; % generate random nuumber from 0-1
if (u <= p) % if random number is <= p
successes++; % count it as a success
endif
end
emperical(i) = successes; % store the number of successful trials in this simulation
end
close all; % close any existing graphs
x_values = [0:n]; % array of x-axis values
hist(emperical, x_values, "facecolor", "r"); % plot empirical data
xlim([-0.5 (n + 0.5)]); % set x-axis to allow for histogram bar widths
hold on; % hold current graph
mean = n * p; % theoretical mean
norm = normpdf(x_values, mean, 1); % normalised y values
plot(x_values, norm, "color", "b"); % plot theoretical distribution
legend('Emprical', 'Theoretical');
end
以下に示すように、この曲線は y 軸に沿って非常に低い高さまでしか伸びていませんが、データセット全体にまたがる方法がわかりません。