Step 6 (bonus)
Bonus: Probability & Bayes' rule
A sensor that's usually right can still leave you unsure. Bayes' rule says how sure, and how evidence adds up.
Which balls are steel?
Some of the balls are steel. They look just like the others, and only steel ones belong in the cup. Between the fingers is a magnetic sensor: pick a ball up and magnet.read() returns True ("steel") or False. It isn't reliable:
| The ball is… | Chance it reads True |
|---|---|
| steel | |
| not steel |
Before any reading, each ball is steel with probability . That's the prior. A probability is a number from 0 (impossible) to 1 (certain).
Bayes' rule
means "the probability of , given that happened". After one reading , the probability that the ball is steel is
The top is the chance of "steel, and it reads ". The bottom adds "not steel, and it reads ": every way of seeing . For one True:
A sensor that's usually right leaves you barely surer than a coin toss, because ordinary balls are more common and fool it 30 % of the time. One False gives 0.11. The result is called the posterior.
Evidence adds up
Readings are independent, so apply the rule again for every new reading, using the last posterior as the next prior. Twenty readings of a steel ball push the posterior close to 1, and of an ordinary ball close to 0. Deciding from one reading per ball sorts all four correctly only about one run in four.
Your task
- Write
posterior(prior, p_hit, p_false, readings): the probability of steel after a list ofTrue/Falsereadings. - The starter picks up each ball, reads the sensor
Ntimes, plots the posterior after each reading, and drops the ball in the cup if the posterior ends above 0.5 (otherwise it puts it back). One reading isn't enough: take 100. Only the steel balls may end in the cup.