Created
January 15, 2014 23:25
-
-
Save Anaphory/8446810 to your computer and use it in GitHub Desktop.
Calculations for non-associativity of dice
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
#!/usr/bin/env python3 | |
import collections | |
class DiscreteProbabilityDistribution: | |
def __init__(self, pdict): | |
try: | |
self.pdict = collections.Counter(pdict) | |
except: | |
self.pdict = collections.Counter({pdict: 1}) | |
def __add__(self, other): | |
pdict = collections.Counter() | |
for i, p in self.pdict.items(): | |
for j, q in other.pdict.items(): | |
pdict[i+j] += p*q | |
return DiscreteProbabilityDistribution(pdict) | |
def __repr__(self): | |
return repr(self.pdict) | |
def mean(self): | |
return sum(i*p for i,p in self.pdict.items()) | |
DPD = DiscreteProbabilityDistribution | |
def d(D): | |
pdict = collections.Counter() | |
try: | |
D.pdict | |
except AttributeError: | |
D=DPD(D) | |
for i, p in D.pdict.items(): | |
for j in range(1,i+1): | |
pdict[j] += p*(1/i) | |
return DPD(pdict) | |
def multi(N, D): | |
pdict = collections.Counter() | |
try: | |
N.pdict | |
except AttributeError: | |
N=DPD(N) | |
Y = max(N.pdict.keys()) | |
x = DPD(0) | |
for i in range(Y+1): | |
for j, p in x.pdict.items(): | |
pdict[j] += p * N.pdict[i] | |
x = x+D | |
return DPD(pdict) | |
print("((1d6)d6)d6: {:f}".format(multi(multi(d(6), d(6)), d(6)).mean())) | |
print("(1d6)d(6d6): {:f}".format(multi(d(6), d(multi(6, d(6)))).mean())) | |
print("1d(6d(6d6)): {:f}".format(d(multi(6, d(multi(6, d(6))))).mean())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment