To see the result simulated, the following codes on MATLAB can help to illustrate that with 1 million trials. Documentations are added to clarify the algorithm.
probability = 0.5; %prob of tossing head
numTrials = 1000000; %number of simulation trials
trialResults = zeros(1,numTrials);
for trial = 1:numTrials
done = false;
lastHead = false;
toss = 0;
while ~done %this loop controls each trial
roll = rand;
toss = toss + 1;
if roll < probability && lastHead
trialResults(trial) = toss;
done = true; %each trial over when last trial was H, and this trial is also
elseif roll < probability && ~lastHead
lastHead = true; %last trial was not H, but this trial is
else
lastHead = false; %did not toss a H
end
end
end
sum(trialResults == 4) / numTrials
The results vary very little from 0.1250.