repl.it
@justinholman/

CoinFlipSim-03

Python

No description

fork
loading
Files
  • main.py
  • line.png
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# import modules
import numpy as np
import random

# initiate variables
simcount = 0
heads = 0
percent_heads = []  # this tells python we want a list
sims = 100

# Simulate flipping a coin repeatedly
for i in range(sims) :
  simcount += 1
  rand1 = random.random()
  if rand1 >= 0.5 :
    heads += 1
  pct_heads = round(heads/simcount,4)
  percent_heads.append(pct_heads)
  #print(pct_heads)

print(percent_heads)
print("sim complete")

#create a line plot with pyplot
import matplotlib.pyplot as plt
plt.plot(percent_heads)
plt.title("Coin Flip Simulation")
plt.xlabel("Number of Coin Flips")
plt.ylabel("% Heads")
plt.ylim(0,1)
plt.axis([0, sims, 0, 1])
plt.grid(True)
plt.show()
plt.savefig('line.png')

print("plot complete")

# this program runs the simulation and saves output to a list variable
# this program also generates a line plot to illustrate how % heads converges to 0.5
# also, you can change the number on line 9 (sims=) to any number