掷骰子并计算频率

时间:2017-06-02 23:20:26

标签: python-3.x

我的目标是创建一个用户输入的骰子滚动模拟器,“滚动次数”,“死亡侧”,以及试验次数。我的部分代码(下半部分有关错误等等)来自一个类我需要帮助才能获得相对频率和实验概率。教授还指出,要获得与他相同的数字,随机数生成器使用整数237.谢谢。

import random

# Sets the number of faces on the dice we are rolling
# Set to 6 for a 6-sided dice, 20 for a 20-sided dice, etc
NumberOfFaces = int(input("How many sides?:"))

face = [] # create a list
# Set the number of elements in the list
for x in range(0, NumberOfFaces):
  face.append(0)

NumberOfRolls = int(input("How many rolls?:"))

for y in range(0, NumberOfRolls):
  # roll the dice with randrange, and then add one to that element of the list
  face[random.randrange(0, NumberOfFaces)] += 1

numberOfTrials = int(input('How many trials? Enter:'))

# print out how many times each face came up 
for z in range(0, NumberOfFaces):
    frequency = (("%d: %d") % (z+1,face[z]))
    #print(frequency)

relativeFrequency = [0, 0]
probability = [0,0]
error = [0,0]
for i in range(2, len(frequency)):
   relativeFrequency.append(frequency/numberOfTrials)
   probability.append(min(i-1,13-i)/36)
   error.append(abs(probability[i]-relativeFrequency[i]))
# end for


#print(relativeFrequency)
#print(probability)
#print(error)
print()


# print results
f1 = "{0:<10}{1:<22}{2:<22}{3:<22}"
f2 = 71*"-"
f3 = "{0:>3}       {1:<22.15f}{2:<22.15f}{3:<.15f}"
print(f1.format("Sum","Relative Frequency","Probability","Error"))
print(f2)
for i in range(2, len(frequency)):
   print(f3.format(i, relativeFrequency[i], probability[i], error[i]))
#end for
print()

我想要的输出

Enter the number of dice: -1
The number of dice must be at least 1
Please enter the number of dice: 4
Enter the number of sides on each die: 1
The number of sides on each die must be at least 2
Please enter the number of sides on each die: 7
Enter the number of trials to perform: -1
The number of trials must be at least 1
Please enter the number of trials to perform: 10000
Sum Frequency Relative Frequency Experimental Probability
----------------------------------------------------------------------
 4 6 0.00060 0.06 %
 5 18 0.00180 0.18 %
 6 52 0.00520 0.52 %
 7 83 0.00830 0.83 %
 8 166 0.01660 1.66 %
 9 273 0.02730 2.73 %
 10 346 0.03460 3.46 %
 11 469 0.04690 4.69 %
 12 630 0.06300 6.30 %
 13 738 0.07380 7.38 %
 14 836 0.08360 8.36 %
 15 930 0.09300 9.30 %
 16 930 0.09300 9.30 %
 17 985 0.09850 9.85 %
 18 844 0.08440 8.44 %
 19 737 0.07370 7.37 %
 20 589 0.05890 5.89 %
 21 526 0.05260 5.26 %
 22 326 0.03260 3.26 %
 23 238 0.02380 2.38 %
 24 124 0.01240 1.24 %
 25 86 0.00860 0.86 %
 26 49 0.00490 0.49 %
 27 13 0.00130 0.13 %
 28 6 0.00060 0.06 %

以下是图片的链接,以便准确了解

期望输出

1 个答案:

答案 0 :(得分:0)

您需要了解“预期”和“观察”之间的区别。如果随机数发生器应该是统一的,我们期望每个骰子都是公平的。假设有多个骰子并且结果增加了,预期分布就是钟形曲线。公式由我们的数学表兄弟给出,这里

https://math.stackexchange.com/questions/1010729/when-rolling-multiple-dice-what-is-the-average-value-if-you-only-keep-the-highe

这比基本数学有点琐碎,但并不是那么复杂。

为了测试试验是否公平,您需要在观察结果和预期结果之间进行卡方检验。