Python繪製直方圖 Pygal模擬擲骰子

右介發表於2018-04-09
#coding=utf-8
from random import randint

class Die():
    """骰子類"""
    def __init__(self, num_sides = 6):
        """預設6面"""
        self.num_sides = num_sides

    def roll(self):
        """返回一個介於1到骰子面數之間得隨機值"""
        return randint(1, self.num_sides)

模擬同時擲兩個6面骰子1000次的結果:

#coding=utf-8
import pygal
from die import Die

# 建立兩個6面骰子
die_1 = Die()
die_2 = Die()

# 擲骰子多次,並將結果存入列表
results = []
for roll_num in range(1000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

# 分析結果
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result+1):
    frequency = results.count(value)
    frequencies.append(frequency)

# 視覺化
hist = pygal.Bar()

hist.title = "Results of two D6 1000 times."
hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
hist.x_title = "Result"
hist.y_title = "frequency of Result"

hist.add('D6 + D6', frequencies)
hist.render_to_file('dice_visual.svg')

 

相關文章