Calculate a probability distribution of totals acquired from rolling an arbitrary number of dice, each with an arbitrary configuration of non-negative, integer face values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
dice = [] #Input dice as polynomial coefficients | |
print "Enter face values as non-negative integers, separated by spaces, commas, or semicolons. (e.g. \"1,2;3 4 5 6\")" | |
while True: | |
rawdie = [] #List of face values | |
qty = 1 #Quantity of a single die spec | |
inp = raw_input("Die " + str(len(dice) + 1) + "? ") | |
if inp == "": | |
break | |
#rawdie = [int(face) for face in inp.split(" ")] | |
rawdie = [int(face.strip()) for face in re.split(" |,|;", inp) if face.strip()] | |
qty = raw_input("Quantity? [1] ") | |
if qty == "": | |
qty = 1 | |
else: | |
qty = int(qty) | |
die = [0] * (max(rawdie) + 1) | |
for i in rawdie: | |
die[i] += 1 | |
dice += [die for i in range(qty)] | |
print(str(rawdie) + " x " + str(qty)) | |
lastresult = dice[0] | |
for current in dice[1:]: | |
result = [0] * (len(lastresult) + len(current) - 1) | |
for x, v1 in enumerate(lastresult): | |
if v1 == 0: | |
continue | |
for y, v2 in enumerate(current): | |
result[x + y] += v1 * v2 | |
lastresult = result | |
skipzero = True | |
p = 0.0 | |
fcum = 0.0 | |
for i in lastresult: | |
p += i | |
print "Permutations: {:.0f}".format(p) | |
print "{:<6} {:<12} {:>10} {:>10} {:>10}".format("Total","Freq","Prob", "p>=", "p<=") | |
for i, f in enumerate(lastresult): | |
fcum += f | |
if f == 0 and skipzero: | |
continue | |
skipzero = False | |
print "{:<6} {:<12} {:>10.3%} {:>10.3%} {:>10.3%}".format(i, f, f / p, (p - fcum + f) / p, fcum / p) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment