gpt4 book ai didi

python-3.x - 掷 S 面 N 个骰子时出现 T 只眼睛的概率

转载 作者:行者123 更新时间:2023-12-01 12:29:08 25 4
gpt4 key购买 nike

我想计算 n 个骰子的所有眼睛的总和与 s 面(编号从 1 到 s) 等于 t。我的语言是 Python 3。

我目前的方法几乎是一种尝试计数的解决方案,只适用于小数字(运行 probability(10, 10, 50) 已经吃掉了我所有的 RAM 并迫使我硬重置):

import itertools
def probability(n, s, t):
all_rolls=list(itertools.product(range(1,s+1), repeat=n))
target_rolls=[l for l in all_rolls if sum(l)==t]
return round(len(target_rolls)/len(all_rolls), 4)

但老实说,我不知道还有什么办法可以解决这个问题。你能帮我走上正轨吗?

最佳答案

itertools.product 对于边数 > 5 和边数 > 6 来说太慢了。在我的机器上,dice_number: 10 和边数: 10 花了一个半小时来计算。相反,我使用了 numpy.polypow函数计算目标,计算时间不到一秒。

from numpy.polynomial.polynomial import polypow

def probability(dice_number, sides, target):
"""
Using numpy polynomial
The number of ways to obtain x as a sum of n s-sided dice
is given by the coefficients of the polynomial:

f(x) = (x + x^2 + ... + x^s)^n
"""

# power series (note that the power series starts from x^1, therefore
# the first coefficient is zero)
powers = [0] + [1] * sides
# f(x) polynomial, computed used polypow in numpy
poly = polypow(powers, dice_number)
return poly[target] / sides ** dice_number if target < len(poly) else 0

关于python-3.x - 掷 S 面 N 个骰子时出现 T 只眼睛的概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36134980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com