简体   繁体   English

"Python - 为掷骰子绘制 for 循环的直方图"

[英]Python - Plotting histogram of a for loop for dice rolls

I am trying to plot a histogram for the sum of 20 dice rolls when the simulation is ran 1000 times.当模拟运行 1000 次时,我试图为 20 次掷骰子的总和绘制直方图。

def dice(n):
total = 0
for i in range(1000):
    total += random.randint(1, 6)
    plt.hist(total)
    plt.title('Outcome of 20 Rolls')
return total    

Try this:试试这个:

def main():
    import random
    import matplotlib.pyplot as plt
    import numpy as np
    #create a list of 20 random numbers between 1 and 6
    dice_rolls = []
    for i in range(1000):
        dice_rolls.append(sum(random.sample(range(1,7),20)))
    #plot a histogram of the list
    plt.hist(dice_rolls,bins=range(2,38))
    plt.xlabel('Sum of 20 dice rolls')
    plt.ylabel('Frequency')
    plt.title('Histogram of Sum of 20 dice rolls')
    plt.show()
import matplotlib.pyplot as plt
import random

def roll(n):
    outcomes = [random.randint(1, 6) for _ in range(n)]
    return sum(outcomes)

rolls = 20
simu = 1000
sums = [roll(rolls) for _ in range(simu)]

plt.hist(sums, bins=40)
plt.title(f"Sum of {rolls} rolls ({simu} times)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM