dudl / random_sampling_and_sampling_variability.py
BytePhantom
up
85c0609
raw
history blame contribute delete
890 Bytes
# %%
# import libraries
import numpy as np
import matplotlib.pyplot as plt
# %%
# create a list of numbers to compute the mean and variance
x = [1,2,4,6,5,4,0,-4,5,-2,6,10,-9,1,3,-6]
n = len(x)
# compute the population mean
popmean = np.mean(x)
# compute a sample mean
sample = np.random.choice(x,size=5,replace=True)
sampmean = np.mean(sample)
# print them
print(popmean)
print(sampmean)
# %%
# compute lots of sample means
# number of experiments tor run
nExpers = 10000
# run the experiment!
sampleMeans = np.zeros(nExpers)
for i in range(nExpers):
# step 1: draw a sample
sample = np.random.choice(x,size=5,replace=True)
# step 2: compute its mean
sampleMeans[i] = np.mean(sample)
# show the results as a histogram
plt.hist(sampleMeans,bins=40, density=True)
plt.plot([popmean,popmean], [0,.3],'m--')
plt.ylabel('Count')
plt.xlabel('Sample mean')
plt.show()
# %%