900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 掷骰子python代码_Python 使用matplotlib模块模拟掷骰子

掷骰子python代码_Python 使用matplotlib模块模拟掷骰子

时间:2022-07-15 04:30:18

相关推荐

掷骰子python代码_Python 使用matplotlib模块模拟掷骰子

掷骰子

骰子类

# die.py 骰子类模块

from random import randint

class Die():

"""骰子类"""

def __init__(self, num_sides=6):

"""默认六面的骰子"""

self.num_sides = num_sides

def roll(self):

"""掷骰子的方法"""

return randint(1, self.num_sides)

折线图掷骰子

# die_visual_plot.py 使用plot可视化骰子

import matplotlib.pyplot as plt

from die import Die

# Initialization

die = Die()

# 掷骰子

results = [die.roll() for x in range(1000)]

# 分析结果

frequencies = [results.count(x) for x in range(1, die.num_sides+1)]

# 可视化结果

values = [x for x in range(1, die.num_sides+1)]

plt.plot(values, frequencies, linewidth=2, marker='o', markerfacecolor='yellow', markersize=5, color='b')

# 设置图表

plt.title('Roll a die using matplotlib', fontsize=24)

plt.xlabel('Value', fontsize=14)

plt.ylabel('Frequency', fontsize=14)

# 显示数据

for x, y in zip(values, frequencies):

# 将y数据加载到(x,y)位置

plt.text(x, y, y, fontsize=12, color='red', ha='center', va='bottom')

# 显示结果

plt.show()

散点图掷骰子

# die_visual_scatter.py 使用scatter可视化骰子

import matplotlib.pyplot as plt

from die import Die

# Initialization

die = Die()

# 掷骰子

results = [die.roll() for x in range(1000)]

# 分析结果

frequencies = [results.count(x) for x in range(1, die.num_sides+1)]

# 可视化结果

values = [x for x in range(1, die.num_sides+1)]

plt.scatter(values, frequencies, c=frequencies, cmap=plt.cm.Blues, edgecolor='none', s=10)

# 设置图表

plt.title('Roll a die using matplotlib', fontsize=24)

plt.xlabel('Value', fontsize=14)

plt.ylabel('Frequency', fontsize=14)

# 显示数据

for x, y in zip(values, frequencies):

# 将y数据加载到(x,y)位置

plt.text(x, y, y, fontsize=12, color='red', ha='center', va='bottom')

# 显示结果

plt.show()

总结

以上所述是小编给大家介绍的Python 使用matplotlib模块模拟掷骰子,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

本文标题: Python 使用matplotlib模块模拟掷骰子

本文地址: /jiaoben/python/267734.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。