Home > Article > Backend Development > How to verify the central limit theorem in python
Python method to verify the central limit theorem: first simulate randomly throwing dice 1000 times and observe the average; then simulate throwing dice ten times and draw a picture to see their distribution; finally simulate 1000 groups, and each group throws 50 times, and take the average of each group to see the distribution.
Python method to verify the central limit theorem:
Central limit theorem:
From a given population obeying any distribution, n samples are drawn each time, m times in total. Then average the values of each group of m, and the average value of each group will obey an approximately normal distribution.
import numpy as np a = np.random.randint(1,7,1000)print(a)a.mean()
Output result:
As you can see, the average value is taken after throwing 1000 times (note: this average value is slightly different every time, because is randomly selected) is close to 3.5 (3.5=1/6*(1 2 3 4 5 6)).
Then, simulate throwing 10,000 times again, and take the average value
You can see that the result is getting closer to 3.5
sample = []for i in range(10): sample.append(a[int(np.random.random()*len(a))]) #从a里面随机抽plt.figure(figsize=(20,10),dpi=100)plt.bar(sample,range(len(sample)))plt.show()
It can be seen that the distribution is not very uniform.
sample_mean=[]sample_std=[]samples=[]for i in range(1000): sample=[] #每组一个列表 for j in range(60): sample.append(a[int(np.random.random()*len(a))])#模拟抛50次 sample = np.array(sample) #转化为array数组,便于处理 sample_mean.append(sample.mean()) sample_std.append(sample.std()) samples.append(sample)sample_mean_np = np.array(sample_mean)sample_std_np = np.array(sample_std)print(sample_mean_np)
plt.figure(figsize=(20,10),dpi=80)d =0.1 num_bins = (max(sample_mean_np)-min(sample_mean_np))//d plt.hist(sample_mean_np,num_bins) #绘制频率分布图
It can be seen that the average value of each group obeys the normal distribution.
Related free learning recommendations: python video tutorial
The above is the detailed content of How to verify the central limit theorem in python. For more information, please follow other related articles on the PHP Chinese website!