Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168731
Image: ubuntu2004
# GAMBLER'S RUIN SIMULATION # We start with a stake of a certain number of dollars, # and then play a betting game where we win or lose a unit of money. # Each time we play, the probability of winning is fixed. # We will draw a graph of our financial position # (imagine we bet once a day, then the x-axis of the graph is days, # and the y-axis is the amount of money we have). start= 100 # start with 100 dollars nBets = 100 # we will bet 100 times betSize = 1 # each bet is for 1 dollar pWin = 0.48 # we win each bet with probability 45% wealth = start # this variable holds our total accumulation. daily =[wealth] # this initializes an array (list), whose first (0th) member is the value of # wealth. Eventually the array will have nBets items, the amount accumulated # each day. # The next line is a looping command. The "_" is just a dummy index variable; it can be given # any name. So the loop means "repeat as many times as the variable nBets." # Notice that after the loop command, there is a colon (":") and then the code automatically # indents. This is how the if and else commands work, as well. for _ in range(nBets): if random()<pWin: # if command; it will be true with probability pWin wealth += betSize # if true, we increment wealth by the betSize value else: # otherwise (note the colon and automatic indent) wealth -= betSize # we decrease wealth by the betSize value daily.append(wealth) # the last line of the loop is to append the current wealth value # to the variable daily (which is a list) # The final lines create a variable for the plot, print out some values, and then display the plot. l=list_plot(daily,plotjoined=True) print('P(win) = %.3g'%pWin) print('Start value: %s' %start) print('End value: %s' %daily[nBets]) show(l)
P(win) = 0.48 Start value: 100 End value: 92
#interactive version (the hashtag precedes comments which SAGE doesn't interpret) @interact def _(pWin=slider(0,1,.01,default=0.48,display_value=False), betSize = [1,10,100], nBets =(100,[1,10,100,1000,5000]),fixedAxis=checkbox(False,"Fixed Axis")): start= 100 wealth = start daily =[wealth] for _ in range(nBets): if random()<pWin: wealth += betSize else: wealth -= betSize daily.append(wealth) l=list_plot(daily,plotjoined=True) if fixedAxis: l.set_axes_range(0,nBets,-1.5*start,1.5*start) print('P(win) = %.3g'%pWin) print('Start value: %s' %start) print('End value: %s' %daily[nBets]) show(l)
r=.52/.48
1/(r^10+1)
0.309934170430358
1/(r^100+1)
0.000333921459253053