Filter löschen
Filter löschen

Simulating 10 biased coin flips 100 times

14 Ansichten (letzte 30 Tage)
Kylenino Espinas
Kylenino Espinas am 25 Feb. 2022
Beantwortet: Voss am 25 Feb. 2022
n = 10; %amount of flips done 1 million times
arr = zeros(n); %array to store heads in n flips
toss = (U < 0.6388888888888); %biased coin toss probability
while j < 10 %Repeating the 10 coin flips 100 times
heads = 0; %Reset heads counter
for i = 1:n %The 10 coin flips
U = rand(0,1); %Rng
if U < 0.6388888888888 %Head/tail counter
heads = heads + 1; %Amount of heads /10 tosses total counter
end
end
arr(heads) = arr(heads) + 1; %accessing point in array and adding one tick
j = j + 1; %ticker for while loop
end
histogram(arr) %graphing
As the title says, I am trying to code 10 coin tosses 100 times. And I am also trying to graph it. However the program enevr runs or graphs correctly. Rather general question but I can't find the error? I think it's the "arr(heads) = arr(heads) + 1" because I've reread it a ton but I'm stuck.

Akzeptierte Antwort

Voss
Voss am 25 Feb. 2022
rand(0,1) returns a 0-by-1 array.
rand() returns a (uniformly distributed) random number between 0 and 1.
See other changes below:
n = 10; %amount of flips done 1 million times
% arr = zeros(n); %array to store heads in n flips
arr = zeros(1,100);
% toss = (U < 0.6388888888888); %biased coin toss probability
j = 1;
% while j < 10 %Repeating the 10 coin flips 100 times
while j <= 100 %Repeating the 10 coin flips 100 times
heads = 0; %Reset heads counter
for i = 1:n %The 10 coin flips
% U = rand(0,1); %Rng
U = rand();
if U < 0.6388888888888 %Head/tail counter
heads = heads + 1; %Amount of heads /10 tosses total counter
end
end
% arr(heads) = arr(heads) + 1; %accessing point in array and adding one tick
arr(j) = heads;
j = j + 1; %ticker for while loop
end
histogram(arr) %graphing
xlabel(sprintf('# of heads in %d coin flips',n))

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by