# proper use of rand for coin toss

Discussion in 'MATLAB' started by chris, Oct 26, 2004.

1. ### chrisGuest

Hi,

This has been bugging me for a while. If I want to simulate a coin
toss using rand, what's the appropriate logical expression for

coin = rand
if coin <0.5
else
toss = tails
end

But this biases toward tails w/the implied >= 0.5.

Looking at the help for rand, it doesn't appear to matter since rand
returns an even number of possible cases. But if rand was continuous
between 0 and 1 inclusive, what would be the appropriate test for

Thanks,

-Chris

chris, Oct 26, 2004

2. ### Ken DavisGuest

In theory, it's irrelevant since the x = 0.5 is an event with probability
zero.

Ken Davis, Oct 26, 2004

3. ### Brett ShoelsonGuest

if coin == 0.5
disp('Omigod! The coin landed on its edge!')'
end

Cheers,
Brett

Brett Shoelson, Oct 26, 2004
4. ### Murphy O'BrienGuest

Yes,

Just to confirm this I'm trying

for i=1:Inf
if (rand==0.5)
disp('Wah Hey!')
end;
end

I wonder how many Wah Heys I'll get?

Murphy

Murphy O'Brien, Oct 26, 2004
5. ### Colin PriestGuest

If it were continuous then the probability of obtaining 0.5 exactly
would be zero

Just resample if you obtain 0.5 exactly.

Colin Priest, Oct 27, 2004
6. ### Brett ShoelsonGuest

Murphy...you fail to appreciate the subtleties of ML. I'm curious how
much time this will save you:

tic;
count = 0;
for ii=1:inf
if rand == 0.5, count = count+1; end
end
t1=toc

tic
a = rand(Inf,1);
count = sum(a==0.5);
t2 = toc

Anxious to get the results...
Brett

Brett Shoelson, Oct 27, 2004
7. ### AJ \no z\ JohnsonGuest

[snip stuff regarding P(rand==0.5)]
My bet is on P(rand==0.5) = 2^-51.

I also guess that rand cannot, ever, return 1, exactly. Or maybe not zero.
If one of those is the case, then the r.v. is being generated over
(0,1]
or
[0,1)
in which case one should one should for heads,
(0,0.5]
or
[0,0.5),
respectively.
respectfully,
Aj

AJ \no z\ Johnson, Oct 27, 2004
8. ### Peter BoettcherGuest

Well, rand only returns stuff between (0,1), so I'll bet instead on
eps(.5) = 1.11e-16. When rand tries to return 0.5 + x, it would
return 0.5 for x < 1.11e-16.

On the other hand 0.5 is an exponent boundary, so 0.5 - x is different
for x > 5.55e-17
In R14, help rand says:

This generator can generate all the floating point numbers in the
closed interval [2^(-53), 1-2^(-53)]. Theoretically, it can generate
over 2^1492 values before repeating itself.

So 0.5 is EXACTLY halfway between the extremes. The only error will
be if MATLAB wants 0.5 - x, x<5.55e-17, since that will look like 0.5.

I think?

Peter Boettcher, Oct 27, 2004