Skip to content

Instantly share code, notes, and snippets.

@kms70847
Created June 7, 2021 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kms70847/427150afd8cd574b8998be41afaf66ed to your computer and use it in GitHub Desktop.
Save kms70847/427150afd8cd574b8998be41afaf66ed to your computer and use it in GitHub Desktop.
bayes.py
#simple implementation of https://en.wikipedia.org/wiki/Bayes%27_theorem
def bayes(p_a, p_b, p_b_a):
"""
arguments:
p_a: P(A), the probability of A
p_b: P(B), the probability of B
p_b_a: P(B|A), the probability of B, given A
returns P(A|B), the probability of A, given B
"""
return p_b_a * p_a / p_b
def coin_problem(x, y, z):
"""
Given:
1) all counterfeit coins come up heads with probability X.
2) all genuine coins come up heads with probability Y.
3) a coin you find on the ground has probability Z of being counterfeit. Equivalently, a coin is genuine with probability 1-Z.
4) You find a coin on the ground and flip it once. The result is heads.
Result:
The probability that your coin is counterfeit.
"""
#let A be "the coin is counterfeit"
#let B be "you flip a coin once and it comes up heads"
p_b_a = x
p_a = z
#formula derived by magic.
p_b = x*z + y*(1-z)
p_a_b = bayes(p_a, p_b, p_b_a)
return p_a_b
test_cases = [
(0.75, 0.5, 0.1, "typical case"),
(0.75, 0.5, 0.9, "the counterfeiter made a whole lot of coins"),
(1, 0.5, 0.1, "the counterfeiter makes only double-headed coins"),
(0, 0.5, 0.1, "the counterfeiter makes only double-tailed coins"),
(0.75, 0.75, 0.1, "the mint isn't very good at balancing coins"),
(0.5, 0.75, 0.1, "counterfeiter wants to show them how it's done")
]
for x,y,z, commentary in test_cases:
print(f"coin_problem({x:.2f}, {y:.2f}, {z:.2f}) == {coin_problem(x,y,z):.4f} \t {commentary}")
"""
output:
coin_problem(0.75, 0.50, 0.10) == 0.1429 typical case
coin_problem(0.75, 0.50, 0.90) == 0.9310 the counterfeiter made a whole lot of coins
coin_problem(1.00, 0.50, 0.10) == 0.1818 the counterfeiter makes only double-headed coins
coin_problem(0.00, 0.50, 0.10) == 0.0000 the counterfeiter makes only double-tailed coins
coin_problem(0.75, 0.75, 0.10) == 0.1000 the mint isn't very good at balancing coins
coin_problem(0.50, 0.75, 0.10) == 0.0690 counterfeiter wants to show them how it's done
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment