In: Math
Consider flipping nn times a coin. The probability for heads is given by pp where pp is some parameter which can be chosen from the interval (0,1)(0,1).
Write a Python code to simulate nn coin flips with heads probability pp and compute the running proportion of heads X¯nX¯n for nn running from 1 to 1,000 trials. Plot your results. Your plot should illustrate how the proportion of heads appears to converge to pp as nn approaches 1,000.
In [ ]:
### Insert your code here for simulating the coin flips and for computing the average
In [2]:
### Complete the plot commands accordingly for also plotting the computed running averages in the graph below
p = 0.25 # just an example
plt.figure(figsize=(10,5))
plt.title("Proportion of heads in 1,000 coin flips")
plt.plot(np.arange(1000),p*np.ones(1000),'-',color="red",label="true probability")
plt.xlabel("Number of coin flips")
plt.ylabel("Running average")
plt.legend(loc="upper right")
The R code for simulating the coin toss is given below. The probability of heads is set at p = 0.25.
You can change the value as you want. The plot shows the probability converges to p = 0.25 as sample size increases.
import matplotlib.pyplot as plt import numpy as np def proportion(seed,n, p): np.random.seed(seed) h = 0 for i in range(n): r = np.random.random_sample(1) if(r<p): h = h+1 return(h/n) N = 1000 p = 0.25 PH = [] seed = 154 for i in range(1,N): ph = proportion(seed,i, p) PH.append(ph) if __name__ == "__main__": plt.figure(figsize=(10,5)) plt.title("Proportion of heads in 1,000 coin flips") plt.plot(range(1,N),PH,'-',color="red",label="True probability") plt.xlabel("Number of coin flips") plt.ylabel("Running average") plt.legend(loc="upper right") plt.show()
Kindly upvote.