定义扔一百次硬币为一组实验。
该代码统计了做两万组试验后,每组实验内正面朝上的频数分布。
目前尚未增加横纵坐标单位长度(有机会更新)。
基于pygame模块。
代码如下:
import pygame, sys
import random
import math
pygame.init()
screen = pygame.display.set_mode([1000,480])
screen.fill([255,255,255])
plotPoints = []
xaxis = [[0,240],[1000,240]]
yaxis = [[500,0],[500,480]]
pygame.draw.lines(screen,[0,0,0],False,xaxis,1)
pygame.draw.lines(screen,[0,0,0],False,yaxis,1)
pairs = {}
for experimentTimes in range(0,20000):
n = 0
for throwTimes in range(0,100):
k = random.randint(0,1)
if k == 1:
n += 1
if not n in pairs.keys():
pairs[n] = 1
elif n in pairs.keys():
pairs[n] += 1
plotPoints = []
for j in pairs.keys():
position = []
position.append(j*10)
position.append(int(-pairs[j]*0.1)+240)
plotPoints.append(position)
plotPoints.sort()
pygame.draw.lines(screen,[0,0,0],False,plotPoints,1)
pygame.display.flip()
running = True
while running :
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
运行效果如下:
每一次运行效果都略有差异。