LearnCoding

Two-proportion z-test for an A/B test

EasyA/B testing, Statistics

Problem

Arm A has conv_a conversions out of n_a, and arm B has conv_b out of n_b. Return (z, p_value) for the pooled two-proportion z-test of B against A (z > 0 when B converts better), with a two-sided p-value from the normal CDF (use math.erf). If the pooled standard error is 0, return (0.0, 1.0).

Signature

def two_proportion_ztest(conv_a: int, n_a: int, conv_b: int, n_b: int) -> tuple[float, float]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> close(two_proportion_ztest(100, 1000, 100, 1000), (0.0, 1.0))
True

>>> close(two_proportion_ztest(100, 1000, 130, 1000), (2.102741, 0.035488))
True

Solve it in your own editor; nothing on this page runs code.

Hints

Pooled p-hat = (x_a + x_b)/(n_a + n_b); SE = sqrt(p-hat (1 - p-hat) (1/n_a + 1/n_b)).

Two-sided p-value = 2 * (1 - Phi(|z|)); use math.erf.

Zero pooled SE -> (0.0, 1.0).

Reference solution

import math

def two_proportion_ztest(conv_a, n_a, conv_b, n_b):
    pa = conv_a / n_a; pb = conv_b / n_b
    p = (conv_a + conv_b) / (n_a + n_b)
    se = math.sqrt(p * (1 - p) * (1 / n_a + 1 / n_b))
    if se == 0:
        return 0.0, 1.0
    z = (pb - pa) / se
    pval = 2 * (1 - 0.5 * (1 + math.erf(abs(z) / math.sqrt(2))))
    return z, pval

What a strong solution covers

  • Pooled p̂ and SE = √(p̂(1−p̂)(1/n_a + 1/n_b)).
  • Correct two-sided p-value 2·(1 − Φ(|z|)).
  • Zero-variance guard.
  • Discusses unpooled SE for confidence intervals, the normal-approximation conditions, peeking, and SRM checks.

Common mistakes

  • one-sided p-values by accident
  • using the unpooled SE in the test statistic without saying so.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.