Can anyone help me solve this coin toss problem. I am a beginner

function cointoss
a=round(rand(1,5000));
b=ones(1,5000);
c=cumsum(a);
d=cumsum(b)
e=a./b
plot(1:5000,e(1,5000),'b')
hold on
plot(1:5000,0.5,'r')
That is the body of my program.
The problem is that computer round my e matrix. Thus, it did not reveal the experimental probability of getting a 'head' after a certain number of trials. How could I solve this problem?
Thanks a lot

 Accepted Answer

As indicated by Image Analyst you had errors in your code. The most important error was writing e = a./b rather than e = c./d . Also there is no point in doing a plot if you only want to compare e(5000) with 1/2. A plot of
plot(1:5000,e,'b')
instead would show how the average improves with an increasing number of tosses.
If after making these corrections it still bothers you that you observe something in the neighborhood of one percent deviation from 1/2 at the far end of the plot in spite of taking 5000 samples, this really shouldn't surprise you. It can be shown that after n coin tosses, you can expect a standard deviation of 1/(2*sqrt(n)) from an average of 1/2, which for n = 5000 would be a little above one percent. To get a really close approximation to the true probability you would need an n of far greater size than 5000.
Roger Stafford

More Answers (2)

Give the command
format long g
and then display e

1 Comment

Thx a lot. Your guys tips already help me solve the problem

Sign in to comment.

Well, close. But try it like this:
clear
clc;
workspace; % Make sure the workspace panel is showing.
format longg;
format compact;
fontSize = 20;
numberOfTosses = 500;
tossSequence = randi(2, 1, numberOfTosses) - 1;
c = cumsum(tossSequence);
d = 1 : numberOfTosses;
headsProbability = c ./ d;
plot(d, headsProbability, 'b', 'LineWidth', 2);
grid on;
fontSize = 20;
xlabel('Number of Tosses', 'FontSize', fontSize);
ylabel('Probability of heads', 'FontSize', fontSize);
title('Coin Toss Monte Carlo Experiment', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);

2 Comments

I correct my own program and it then runs successfully. But, I just tried your program too, and it looks like the 'randi' function does not exist.Is that a typo?
You must have a really old version of MATLAB. It's been in there for a while. No it's not a typo - I just copied and pasted a fully functional script.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!