Created
September 29, 2018 06:22
-
-
Save zazazack/dd15a074af5808f8acc8fe3e9f7086b6 to your computer and use it in GitHub Desktop.
Just about the most satisfying piece of code I've ever written.
This file contains hidden or 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 | |
from fractions import Fraction | |
from itertools import product | |
import statistics | |
import random | |
import logging | |
from matplotlib import pyplot as plt, style | |
logging.basicConfig(level=logging.DEBUG) | |
def probability(event, sample_space): | |
return Fraction(len(event), len(sample_space)) | |
def trial(S): | |
return random.choice(S) | |
def simulate(n): | |
for i in range(n): | |
yield trial(S) | |
if __name__ == '__main__': | |
# sample space, i.e. all possible outcomes | |
# NOTE: _Not_ a set of "intermediate results", but of the same "type" as the | |
# results contained in A _and_ can be "filtered" by a boolean | |
S = [sum(i) for i in product({*range(1, 7)}, range(1, 7))] | |
assert len(S) == 6 * 6 # i.e. 2 six-sided die | |
assert probability(S, S) == 1 # rule | |
A = list(filter(lambda x : x <= 9, S)) | |
P = probability(A, S) | |
P | |
plt.hist(S) | |
plt.hist([*simulate(100)]) | |
plt.hist([*simulate(1000)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment