Problem 520584 · medium · Level 05 Advanced Algorithms & Graphs

How Likely Is the Seed Better Than Half?

Bayesian updating · Beta distribution · credible interval · binomial distribution · bisection

A seed company is testing a new drought-resistant variety. Of the seeds planted, yes germinated and no did not. Before the trial, the breeders' belief about the germination rate θ was Beta(a, b); after it, the belief is Beta(A, B) with A = a + yes and B = b + no. The breeders want answers about θ itself: "how likely is it that more than half of these seeds germinate?" and "between which values does θ lie with 95% probability?"

Write seed_posterior(a, b, yes, no, threshold, level) that returns a dict:

  • "posterior": the tuple (A, B),
  • "mean": the posterior mean A / (A + B),
  • "p_above": the posterior probability that θ > threshold,
  • "interval": the equal-tailed credible interval (low, high) with posterior probability (1 - level) / 2 below low and the same above high.

All parameters are whole numbers, and every answer must be accurate to within 1e-6. No statistics library is needed: a Beta distribution with whole-number parameters is linked to the binomial distribution, and the hints show how.

Examples

Input:  a = 1, b = 1, yes = 7, no = 3, threshold = 0.5, level = 0.95
Output: {"posterior": (8, 4), "mean": 0.6666666666666666, "p_above": 0.88671875,
         "interval": (0.3902574404275787, 0.8907365561809)}
Explanation: with a flat prior and 7 of 10 germinating, there is an 88.7% probability
that the rate is above one half, and a 95% probability that it lies between 0.39 and 0.89.

Input:  a = 2, b = 8, yes = 3, no = 1, threshold = 0.5, level = 0.9
Output: {"posterior": (5, 9), "mean": 0.35714285714285715, "p_above": 0.1334228515625,
         "interval": (0.1656594267150719, 0.5726193394082149)}

Constraints

  • a, b >= 1, yes, no >= 0 (whole numbers), A + B <= 5000
  • 0 < threshold < 1, 0 < level < 1
  • floats are compared with a tolerance of 1e-6

Goals

  • Turn a Beta prior and yes/no data into a Beta posterior
  • Compute probabilities under a Beta distribution with integer parameters exactly
  • Find the equal-tailed credible interval by searching for quantiles
Starting Python…