模拟投骰子并可视化

2020-06-12 16:15:21 浏览数 (1)

安装pygal库

首先创建一个骰子的类:

代码语言:javascript复制
from random import randint
class Die():
    """表示一个骰子的类"""
    def __init__(self, num_sides = ):
        """色子默认6面"""
        self.num_sides = num_sides
    def roll(self):
        """方法roll返回一个位于1和骰子面数之间的随机值"""
        return randint(, self.num_sides)
  • 来一个简单的6面骰子,投掷10000次并将频数结果可视化
代码语言:javascript复制
from die import Die
import pygal
# 创建一个6面骰子的实例
die_6 = Die()
num_throw = 
results = [die_6.roll() for i in range(num_throw)]
frequencies = [results.count(value) for value in range(,die_6.num_sides )]
hist = pygal.Bar()
hist.title = "Frequencies of 6-sides throw %d times" % num_throw
hist.x_lables = list(range(,die_6.num_sides ))
hist.x_title = "Result"
hist.y_title = "Frequencies of each value"
hist.add("D6",frequencies)
hist.render_to_file("D6_%d.svg" % num_throw)
hist.render_to_png("D6_%d.png" % num_throw)
  • 看下结果:

这便是一个6面骰子10000次投掷后的频数统计。

  • 再来看下2个6面的骰子点数统计会是如何的呢?
代码语言:javascript复制
import pygal
from die import Die
die1 = Die()
die2 = Die()
num_throw = 

results = [die1.roll()   die2.roll()
           for num in range(num_throw)]
frequencies = [results.count(value)
               for value in range
               (, die1.num_sides die2.num_sides )]
hist = pygal.Bar()
hist.title = 'Results of two D6 throw %d times' % num_throw
hist.x_labels = list(range(, die1.num_sides die2.num_sides ))
hist.x_title = "Results"
hist.y_title = "Frequency of value"
hist.add('D6 D6', frequencies)
hist.render_to_file('D6_D6.svg')
hist.render_to_png('D6-D6_%d.png' % num_throw)
  • 我们来看下结果:

再来看下2个骰子投1000000次呢?我们只需要见num_throw = 1000000再运行程序就行了。看下结果:

0 人点赞