Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
dicey formula and scipy.product solution in Clear category for Probably Dice by quarkov
from math import factorial as f
from scipy import product as p
def probability(n, s, target):
if 1 * n > target or target > s * n: return 0.0
total_rolls, lucky_rolls = s**n, 0
for k in range(((target-n)//s) + 1):
a = (-1)**k * f(n) / (f(k) * f(n-k))
b = p([(target - s*k - i) / i for i in range(1, n)])
lucky_rolls += a * b
return round(lucky_rolls/total_rolls, 4)
"""
----------------------------------------------------
A straightforward solution I came up in first place.
It doesn't fit for big n-s obviously.
----------------------------------------------------
from itertools import product
def probability(n, s, target):
if 1 * n > target or target > s * n: return 0.0
if n == 1: return round(n/s, 4)
outcomes = [x for x in range(1, s+1) if target > x >= target - (n-1) * s]
for i in range(1, n):
outcomes = [sum(seq) for seq in product(outcomes, range(1, s+1)) if sum(seq) <= target]
return round(outcomes.count(target)/(s**n), 4)
"""
March 17, 2019