die.py
from random import randint
class Die:
def __init__(self, num_sides = 6):
# 骰子默认6面
self.num_sides = num_sides
def roll(self):
# 返回一个位于1-6的随机值
return randint(1, self.num_sides)
die_sample.py
from plotly.graph_objs import Bar, Layout
from plotly import offline
from die import Die
# 创建一个Die实例
A = Die()
B = Die(10)
# 存储投掷所得到的结果
results = []
for i in range(1000):
result = A.roll() + B.roll()
results.append(result)
# 分析每种点数出现的次数
frequencies = []
max_result = A.num_sides + B.num_sides
for value in range(2, max_result + 1):
frequency = results.count(value)
frequencies.append(frequency)
# 对结果进行可视化
x_values = list(range(2, max_result + 1))
data = [Bar(x = x_values, y = frequencies)]
x_axis_config = {'title': '结果', 'dtick': 1}
y_axis_config = {'title': '结果的频率'}
my_Layout = Layout(title = '掷1个D6和1个D10,1000次的结果',
xaxis = x_axis_config, yaxis = y_axis_config)
offline.plot({'data': data, 'layout': my_Layout}, filename = 'D6_D10.html')
效果图:
|