Decide if a new prompt really converts better with a two-proportion z-test

You ship prompt A to some users and prompt B to others and count how many convert. B looks better, but is it noise? The two-proportion z-test answers that.

Write ab_test(conv_a, n_a, conv_b, n_b) that returns (z, p_value):
- pooled p = (conv_a + conv_b) / (n_a + n_b)
- se = sqrt(p (1 - p) (1 / n_a + 1 / n_b))
- z = (rate_b - rate_a) / se
- p_value is two-sided: 2 (1 - Phi(|z|)), where Phi is the standard normal CDF.

Use math.erf for Phi: Phi(x) = 0.5 (1 + erf(x / sqrt(2))).

Signaturedef ab_test(conv_a, n_a, conv_b, n_b)

Understand the idea

A two-proportion z-test asks whether the difference between two conversion rates is bigger than random noise would usually give. Assume first that A and B are the same and pool them to estimate one shared rate. Then measure the gap in rates in units of standard error. Worked example: A converts 50 of 1000 (5%), B converts 70 of 1000 (7%). Pooled p = 120 / 2000 = 0.06. se = sqrt(0.06 x 0.94 x (1/1000 + 1/1000)) = sqrt(0.0001128) = 0.01062. z = (0.07 - 0.05) / 0.01062 = 1.883. Two-sided p-value = 2 x (1 - Phi(1.883)) = 0.0597, so not significant at 0.05. Rule: p = total conversions / total users; se = sqrt(p(1 - p)(1/n_a + 1/n_b)); z = (rate_b - rate_a) / se; p_value = 2(1 - Phi(|z|)) with Phi(x) = 0.5(1 + erf(x / sqrt 2)). Product teams use this to judge prompt or UI experiments.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: clear winnerab_test(100, 1000, 150, 1000)
  • Sample 2: noiseab_test(50, 500, 55, 500)
  • Test 3: B worse gives negative zab_test(80, 400, 60, 400)