---
title: Two-proportion z-test for an A/B test
url: https://gurkanozkan.ai/learn/coding/mle-two-proportion-z-test-for-an-a-b-test-38/
markdown: https://gurkanozkan.ai/learn/coding/mle-two-proportion-z-test-for-an-a-b-test-38.md
kind: coding
difficulty: Easy
topics:
  - A/B testing
  - Statistics
json: https://gurkanozkan.ai/api/learn/coding/mle-two-proportion-z-test-for-an-a-b-test-38.json
robots: noindex
---

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

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

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

## Examples

Each call and the value it should give.

```python
>>> 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
```

## Hints

1. Pooled p-hat = (x_a + x_b)/(n_a + n_b); SE = sqrt(p-hat (1 - p-hat) (1/n_a + 1/n_b)).
2. Two-sided p-value = 2 * (1 - Phi(|z|)); use math.erf.
3. Zero pooled SE -> (0.0, 1.0).

## Reference solution

```python
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.*
