A poll's interval and its sample size

A poll finds x people out of n saying yes. Give the estimate with its 95% interval, and say how many people a given margin would need.

What to build

A program for a proportion's confidence interval and sample size.

Requirements

  • Print p-hat P (3 decimal places), 95% CI: L to U (3 decimal places, cut to stay between 0 and 1) and n for margin M: N, the smallest sample whose 95% margin is at most M even in the worst case p = 0.5.

Input

One line: x, n and the margin M.

Output

Three lines.

Constraints

0 ≤ x ≤ n ≤ 10⁶; 0 is less than M, and M is less than 1.

Example

Input:

520 1000 0.03

Output:

p-hat 0.520
95% CI: 0.489 to 0.551
n for margin 0.03: 1068

Why it works

A proportion is the mean of yes-or-no values, so the central limit theorem applies with variance p(1 − p), which is largest at p = 0.5, the safe choice when planning.

Examples

Example 1 · Input
520 1000 0.03
Expected output
p-hat 0.520
95% CI: 0.489 to 0.551
n for margin 0.03: 1068
Example 2 · Input
45 50 0.05
Expected output
p-hat 0.900
95% CI: 0.817 to 0.983
n for margin 0.05: 385

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

p̂ = x ÷ n and SE = √(p̂ (1 − p̂) ÷ n); keep the interval between 0 and 1.

Hint 2

Sample size for margin m: the smallest whole number at least 1.96² × 0.25 ÷ m² (subtract 0.000000001 before rounding up).

Solution

Show one correct solution (try it yourself first)
from math import ceil

x, n, m = input().split()
x, n, m = int(x), int(n), float(m)
p = x / n
se = (p * (1 - p) / n) ** 0.5
print(f"p-hat {p:.3f}")
print(f"95% CI: {max(0.0, p - 1.96 * se):.3f} to {min(1.0, p + 1.96 * se):.3f}")
print(f"n for margin {m}: {ceil(1.96 ** 2 * 0.25 / m ** 2 - 1e-9)}")

Lesson: Confidence intervals →