Sheldon Ross 10: Exercise 3.27

Question: A coin that comes up heads with probability p is continually flipped until the pattern , T, H appears. (That is, you stop flipping when the most recent flip lands heads, the two immediately preceding it lands tails.) Let X denote the number of flips , and find E[X].


Simulation Solution: This problem has a similar structure as the previous one. So, I have just included the simulation for this along with the code needed.


Code: There are two blocks of code, Python (for simulation) and Mathematica (for plots)

from sys import stdout
from mathematica.lists import Range
import csv
from mathematica.sheldon_ross_support_functions import randomChoiceCustom

_folderPath = 'your_path_here'

_csvfile = open(_folderPath + 'sheldon_ross_10_exercise_3.27.csv', 'w', newline='')
_csvWriter = csv.writer(_csvfile)

_steps = 10000
_subSteps = _steps // 100
_progressPadTop = "-" * 106
_progressPadBottom = "-" * 106
_masterList = []

print("\n\nWriting data to the file :" + _csvfile.name)
print(_progressPadTop)

for i in range(0, _steps):
    _gamesMaster = []
    for _p in Range(0.1, 0.95, 0.05):
        _games = []
        while True:
            _games.append(randomChoiceCustom(_p))
            if _games[-3:] == [0, 0, 1]:
                break
        _gamesMaster.append(_games.__len__())

    _csvWriter.writerow(_gamesMaster)

    if (i + 1) % _subSteps == 0:
        stdout.write("\r" + ("\r" + ("#" * (i // _subSteps + 1)).ljust(100)) + " " + str(i // _subSteps + 1) + " %")
        stdout.flush()

print("\n" + _progressPadBottom)
print("Closing the file: " + _csvfile.name)

_csvfile.close()
Needs["JLink`"]
SetOptions[InstallJava, JVMArguments -> "-Xmx8g"];
SetOptions[ReinstallJava, JVMArguments -> "-Xmx8g"];
ReinstallJava[];
SetOptions[$FrontEndSession, EvaluationCompletionAction -> {"ScrollToOutput"}]

Module[
  {data = Transpose@Import[FileNames["*.csv", NotebookDirectory[]][[1]]],
    chartLabels = (Rotate["\!\(\*SubscriptBox[\(p\), \(A\)]\) = " <> ToString[#], Divide[\[Pi], 8]]) & /@ Range[0.1, 0.9, 0.05],
    max = 500},

  DistributionChart[
    data,
    ImageSize -> 788,
    ChartElementFunction -> "SmoothDensity",
    ChartBaseStyle -> Opacity[0.5],
    GridLines -> {None, Range[25, max, 25]},
    ChartLabels -> chartLabels,
    AspectRatio -> 1,
    PlotRange -> {All, {0, max}}
  ]
]

End of the post 😀


.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.