完成作业:掷骰子概率

2024-05-16 07:18:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为班级布置作业。我重新编辑了我的帖子,以显示我想要的结果。到目前为止,我还停留在频率部分。我想达到以下结果: Results

谢谢你!在

随机导入

num = int(input("How many times would you like to roll the dice? "))
sides = int(input("How many sides does the dice have? "))

def throwDice(num=1, sides=6):
    return [random.randint(1,sides) for i in range(num)]


#-- main ----------------------------------------------------------------------   

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



# perform simulation, record and print frequencies
frequency= 13*[0]  # same as [0,0,0,0,0,0,0,0,0,0,0,0,0]

for i in range(numberOfTrials):
   t = throwDice()
   frequency[t[0]+t[0]] += 1;

# end for
print()
print("Frequencies:")
print(frequency)


# calculate relative frequencies, probabilities and errors
relativeFrequency = [0, 0]
probability = [0,0]
error = [0,0]
for i in range(2, len(frequency)):
   relativeFrequency.append(frequency[i]/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()

Tags: inforinputrangeerrornummanyhow
2条回答

t是一个int,因此t[0]没有有效的含义。在

是的。看看你的日常生活:

def throwDice(rolls=1, dice_sides=6):
    results = 0
    throwDice = 0
    for i in range(0, rolls):
            results = random.randint(1, dice_sides)
    return throwDice

。。。在

^{pr2}$

您制作给定数量的纸卷,最后一卷保留在results。然后忽略该值并返回最初分配给局部变量0(顺便说一下,它在本地禁用了函数定义)。然后将0返回到调用程序。在

不能接受整数的第一个和第二个元素。在

你怎么会在不知道你的函数功能不正常的情况下积累了这么多代码?在你继续之前,试着测试小黑人。事实上,试着做些测试:几分钟内准备好打印语句就可以指出问题所在。查看这个可爱的debug博客寻求帮助。在

相关问题 更多 >