In [1]:
#Running this cell displays a button to toggle hidden code
#From: http://chris-said.io/2016/02/13/how-to-make-polished-jupyter-presentations-with-optional-code-visibility/

from IPython.display import HTML

HTML('''<script>
function code_toggle() {
if (code_shown){
$('div.input').hide('500');$('#toggleButton').val('Show Code')
} else {
$('div.input').show('500');$('#toggleButton').val('Hide Code')
}
code_shown = !code_shown
}

$( document ).ready(function(){ code_shown=false;$('div.input').hide()
});
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form>''')

Out[1]:

# Central Limit Theorem Experiments¶

Please note: If you have hidden the code using the toggle in the cell above, the cells will appear as an empty line. However, they can still be run by pressing shift-enter with the empty cell selected.

### Experiment 1(a):¶

Toss a fair coin. If it lands heads, you win 100 dollars, and if it lands tails, you win 0 dollars. Run this experiment X times, where X is chosen by the user. We get a graph of the results, and discover that we get roughly a mean of 50 dollars and a standard deviation of 50 dollars.

Note: In this plot and all others, the mean will be displayed as a vertical red line, and one standard deviation away from the mean on both sides will be displayed as a horizontal red line.

In [2]:
#EXPERIMENT 1A

#SETUP

import numpy as np
import plotly
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected=False)
%matplotlib inline

#Takes input from the user for the value of X:
print("How many times would you like to run the experiment? ")
X = int(input())
X1 = X

#Stores the data on wins and losses:
win_data = []

#Performs the experiment X times:
for n in range(0, X):

#Flips a coin. 100 represents heads, 0 represents tails:
flip = np.random.choice((100, 0))

#Updates win_data with a win or a loss:
win_data.append(flip)

#Calculates the mean:
mean = np.mean(win_data)

#Calculates the standard deviation:
sd = np.std(win_data)

#Graphs a histogram of the data:
data = [go.Histogram(x = win_data, xbins=dict(
start=-10,
end=110,
size=10
))]

title = "Experiment 1(a) Winnings (Mean: {0:.2f}, Standard deviation: {1:.2f})".format(mean, sd)

layout = go.Layout(
title=title,
xaxis=dict(
title='Winnings',
range = [0,110],
fixedrange = True,
),
yaxis=dict(
title='Count',
fixedrange = False
),
shapes=[dict({
'type': 'line',
'x0': mean,
'y0': 0,
'x1': mean,
'y1': 1,
'xref': 'x',
'yref': 'paper',
'line': {
'color': '#f44242',
'width': 3
}}),
dict({
'type': 'line',
'x0': mean - sd,
'y0': 0,
'x1': mean + sd,
'y1': 0,
'line': {
'color': '#f44242',
'width': 10
}})]
)

fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='Experiment 1 Data')