Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Polynomial coefficients solution in Clear category for Probably Dice by rodka81
from numpy.polynomial.polynomial import polypow
def probability(dice_number, sides, target):
""" 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)
# check if the target is in valid range
# if an IndexError is raised, it means that the target cannot be reached,
# therefore the probability is 0
try:
return poly[target] / sides ** dice_number
except IndexError:
return 0
Jan. 5, 2017
Comments: