import matplotlib.pyplot as plt
from random import randint
import numpy as np
classDie:"""模拟投掷筛子"""def__init__(self,num_sides=6):
self.num_sides=num_sides
defroll(self):return randint(1,self.num_sides)
num=100000#投掷1000次
num_sides=12
results=[]
die=Die(num_sides)#创建一个6面筛子for value inrange(num):
results.append(die.roll())
frequencies=[]for i inrange(1,num_sides+1):
frequencies.append(results.count(i))
fig,ax =plt.subplots()
x_values=list(range(1,num_sides+1))
p=ax.bar(x_values,frequencies,label='frequency')
ax.set_title("The frequency of chromophores")
ax.set_xlabel('surface')
ax.set_ylabel('quanity')#设置bar的格式
ax.bar_label(p,label_type='edge')
ax.legend()
plt.show()
投掷两个筛子
import matplotlib.pyplot as plt
from random import randint
import numpy as np
classDie:"""模拟投掷筛子"""def__init__(self,num_sides=6):
self.num_sides=num_sides
defroll(self):return randint(1,self.num_sides)
num=100000#投掷1000次
num_sides=6
results=[]
die=Die(num_sides)#创建一个6面筛子
die1=Die(num_sides)for value inrange(num):
results.append(die.roll()+die1.roll())
frequencies=[]for i inrange(1,num_sides*2+1):
frequencies.append(results.count(i))#绘图
fig,ax =plt.subplots()
x_values=list(range(1,num_sides*2+1))
p=ax.bar(x_values,frequencies,label='frequency')
ax.set_title("The frequency of chromophores")
ax.set_xlabel('surface')
ax.set_ylabel('quanity')
ax.set_xticks(x_values)#设置bar的格式
ax.bar_label(p,label_type='edge')
ax.legend()
plt.show()
重构代码
import matplotlib.pyplot as plt
from random import randint
import numpy as np
classDie:"""模拟投掷筛子"""def__init__(self,num_sides=[6]):
self.num_sides=num_sides
self.results=[]defroll(self):"""返回投掷筛子的总点数"""
result=0for value in self.num_sides:
result+=randint(1,value)return result
defroll_many(self,num=1000):"""投掷多次返回每次投掷的结果"""for value inrange(num):
self.results.append(self.roll())return self.results
defget_sum(self):"""返回点数的最大和"""
sum_=0for value in self.num_sides:
sum_+=value
return sum_
defget_frenquencies(self):"""获得每个点数出现的频次"""
frequencise=[]
sum_=self.get_sum()for i inrange(1,sum_+1):
frequency=self.results.count(i)
frequencise.append(frequency)return frequencise
num=100000#投掷1000次#可以投掷任意数量的筛子
num_sides=[6,6,2]
die=Die(num_sides=num_sides)
results=die.roll_many(num)
frequencise=die.get_frenquencies()print(frequencise)#绘图
fig,ax =plt.subplots()
x_values=list(range(1,die.get_sum()+1))
p=ax.bar(x_values,frequencise,label='frequency')
ax.set_title("The frequency of chromophores")
ax.set_xlabel('surface')
ax.set_ylabel('quanity')
ax.set_xticks(x_values)#设置bar的格式
ax.bar_label(p,label_type='edge')
ax.legend()
plt.show()