Overview
A test ends in one of two decisions, and the truth is one of two states, so there are four outcomes. Two are correct. A Type I error is a false alarm: the null was true and you rejected it. A Type II error is a miss: the null was false and you did not reject it. You set the false alarm rate directly. The miss rate is not set. It follows from , the size of the true effect and the sample size. Power is , the chance of catching a real effect. For a fixed sample, lowering one error rate raises the other, and the only way to lower both is to collect more data. The template works this out exactly for the test with known standard deviation.
A short history
Jerzy Neyman and Egon Pearson introduced the two kinds of error in papers of 1928 and 1933. Fisher's significance tests considered only the null hypothesis; Neyman and Pearson added an explicit alternative, which made it possible to ask how often a test misses a real effect. They proposed fixing the rate of the first kind of error, alpha, and then choosing the test that minimises the second, beta. The idea of power, one minus beta, and of sample size planning comes from this work.
How it works
- Set and the alternative. These fix the critical values of the statistic.
- Express the true effect as a standardised effect size , the distance from the null mean in units of .
- Under that effect the statistic is still normal with variance 1, but centred at instead of 0.
- Power is the probability that this shifted statistic falls in the rejection region.
- The Type II error rate is .
- For planning, search for the smallest whose power reaches the target, commonly 0.8.
Watch out for
- A non-significant result from a low-powered test says almost nothing, because the test would probably have missed a real effect too.
- Power depends on the assumed effect size. An optimistic guess leads to a sample too small for the effect that really exists.
- Pushing very low to avoid false alarms raises at a fixed sample size, so the cost appears as missed discoveries.
- The formulas are for a test with known standard deviation. A test needs slightly more observations, so treat the sample size here as a lower estimate.
Use cases
When to use it
Planning a study or experiment: deciding how many observations are needed so that a real effect of a given size is likely to be detected, and judging what a non-significant result can and cannot tell you.
In industry
- Medical screening
- A screening test weighs false positives, which lead to needless follow up, against false negatives, which miss disease.
- Clinical trial design
- Trials are sized so that the Type I error rate is 5 percent and power is commonly 80 or 90 percent for a clinically relevant effect.
- Fraud and spam detection
- Teams choose an alert threshold by trading blocked legitimate transactions or messages against fraud or spam that gets through.
Choosing it: what must hold
- A decision framed as two hypotheses, with a rule that chooses between them.
- An effect size that matters in practice, so that beta and power can be calculated.
- Some estimate of the cost of each kind of error in the application.
- Control over sample size, or acceptance that a small sample means low power.
When to choose something else
| If | Use instead |
|---|---|
| You need to choose the false alarm rate itself | Significance level (alpha) |
| Many hypotheses are tested and the share of false discoveries matters more | False discovery rate control |
| You are evaluating a classifier, not a statistical test | A confusion matrix with precision and recall |
Math foundations
The two error rates
Each rate is conditional on a different state of the world, so they do not add to 1. is chosen. depends on how false the null is and on how much data you have.
Effect size and the shifted statistic
When the true mean is instead of , the statistic keeps its shape and slides sideways by . Both a larger effect and a larger sample push it further from zero.
Power, one-sided test
For the alternative
greater: the chance that the shifted statistic exceeds the cutoff . At it reduces to .Power, two-sided test
The statistic can land in either rejection tail. For an effect of any real size the second term, the wrong-direction tail, is tiny, and the first term carries the power.
Sample size for a target power
Found by solving the two-sided power formula for with the tiny second term dropped, then rounding up. Halving the effect size quadruples the sample needed. The template finds the exact smallest by search.
Symbols
- Type I error rate, the significance level
- Type II error rate
- power: the probability of detecting a real effect
- true mean and the mean claimed by the null
- known population standard deviation
- standardised effect size
- sample size
- sample mean and the z statistic, as random quantities
- quantile q of the standard normal distribution
- standard normal cumulative distribution function
Worked by hand
A two-sided test at with effect size and . Use , and .
With 25 observations the test detects this effect about 71% of the time and misses it about 29% of the time. Reaching 80% power takes 32 observations.
Visual example
Loading the example.
Try this
- Lower α from 0.05 to 0.005 and watch β grow as the cutoff moves right.
- Raise n until the power passes 0.8, then compare with the sample size in the readout.
- Set the effect size to 0: the two curves coincide and the only possible error is a false alarm.
Code sample
from impl import TypeErrors
from config import TypeErrorsConfig
errors = TypeErrors(TypeErrorsConfig(alpha=0.05, alternative="two-sided"))
print(errors.power(effect_size=0.5, n=25)) # 0.705
print(errors.type_ii_rate(effect_size=0.5, n=25)) # 0.295
print(errors.required_sample_size(effect_size=0.5, power=0.8)) # 32
print(errors.simulate(effect_size=0.0, n=25)) # close to alphaRead the implementation (119 lines)
"""Type I and Type II errors for the z test of a mean: alpha, beta, power and sample size.
NumPy and the standard library only. The normal distribution function comes from `math.erfc` and its quantile
from bisection.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import TypeErrorsConfig
except ImportError: # run from the template's own folder
from config import TypeErrorsConfig
def norm_cdf(z: float) -> float:
"""P(Z <= z) for a standard normal Z."""
return 0.5 * math.erfc(-z / math.sqrt(2.0))
def norm_sf(z: float) -> float:
"""P(Z > z) for a standard normal Z (the upper tail)."""
return 0.5 * math.erfc(z / math.sqrt(2.0))
def _bisect(fn, lo: float, hi: float) -> float:
"""Root of the increasing function `fn` on [lo, hi], by bisection."""
for _ in range(100):
mid = 0.5 * (lo + hi)
if fn(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def norm_ppf(p: float) -> float:
"""Quantile of the standard normal: the z with P(Z <= z) = p, for 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError(f"p must be in (0, 1), got {p}")
if p > 0.5:
return -norm_ppf(1.0 - p)
return _bisect(lambda z: norm_cdf(z) - p, -40.0, 0.0)
class TypeErrors:
"""Error rates of the z test of H0: mean = mu0, with known standard deviation.
The effect size d is (true mean - mu0) / sigma, so the z statistic is centred at d * sqrt(n).
"""
def __init__(self, config: TypeErrorsConfig | None = None) -> None:
self.config = config or TypeErrorsConfig()
def critical_values(self) -> tuple[float, float]:
"""(lower, upper): the test rejects when z falls below `lower` or above `upper`."""
a = self.config.alpha
if self.config.alternative == "two-sided":
upper = norm_ppf(1.0 - a / 2.0)
return -upper, upper
if self.config.alternative == "greater":
return -math.inf, norm_ppf(1.0 - a)
return norm_ppf(a), math.inf
def type_i_rate(self) -> float:
"""Probability of rejecting H0 when it is true. Equal to alpha by construction."""
lower, upper = self.critical_values()
return norm_cdf(lower) + norm_sf(upper)
def power(self, effect_size: float, n: int) -> float:
"""Probability of rejecting H0 when the true standardised effect is `effect_size` and the sample has n values."""
if n < 1:
raise ValueError("n must be at least 1")
lower, upper = self.critical_values()
shift = effect_size * math.sqrt(n)
return norm_cdf(lower - shift) + norm_sf(upper - shift)
def type_ii_rate(self, effect_size: float, n: int) -> float:
"""beta: probability of failing to reject H0 when the true effect is `effect_size`. beta = 1 - power."""
return 1.0 - self.power(effect_size, n)
def required_sample_size(self, effect_size: float, power: float = 0.8) -> int:
"""Smallest n whose power for the given effect size reaches `power`."""
if effect_size == 0:
raise ValueError("effect_size must not be zero: no sample size detects a null effect")
if not self.config.alpha < power < 1.0:
raise ValueError("power must be between alpha and 1")
if self.config.alternative == "greater" and effect_size < 0 or self.config.alternative == "less" and effect_size > 0:
raise ValueError("the effect points away from the one-sided alternative, it cannot be detected")
n = 1
while self.power(effect_size, n) < power:
n *= 2
lo, hi = n // 2, n # power(lo) < target <= power(hi), unless n == 1
while hi - lo > 1:
mid = (lo + hi) // 2
if self.power(effect_size, mid) < power:
lo = mid
else:
hi = mid
return hi
def outcome_table(self, effect_size: float, n: int) -> dict:
"""The four outcomes of a test as probabilities, conditional on which hypothesis is true."""
power = self.power(effect_size, n)
alpha = self.type_i_rate()
return {
"h0_true": {"reject (type I error)": alpha, "fail to reject (correct)": 1.0 - alpha},
"h1_true": {"reject (correct, power)": power, "fail to reject (type II error)": 1.0 - power},
}
def simulate(self, effect_size: float, n: int) -> float:
"""Share of simulated experiments in which the test rejects H0.
Each of `trials` experiments draws n values from a normal distribution with mean `effect_size`
and standard deviation 1 and tests H0: mean = 0. With effect_size = 0 the result estimates the
Type I error rate, otherwise the power (one minus the Type II error rate).
"""
rng = np.random.default_rng(self.config.seed)
z = rng.normal(effect_size, 1.0, size=(self.config.trials, n)).mean(axis=1) * math.sqrt(n)
lower, upper = self.critical_values()
return float(np.mean((z < lower) | (z > upper)))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
With TypeErrors() call power(0.5, 25), type_ii_rate(0.5, 25) and required_sample_size(0.5, 0.8) and check the worked example. Confirm the power with simulate(0.5, 25) and the false alarm rate with simulate(0.0, 25). Then print outcome_table(0.5, 25) for alpha of 0.05 and of 0.01 and see how the two error rates trade off.
Check on learning
- At a fixed sample size, why does lowering from 0.05 to 0.01 raise ? Explain with the picture of two overlapping bell curves and a cutoff.
A way to think about it
One curve is the statistic under the null, the other under the alternative. Move the cutoff away from the null curve and see which area under the other curve grows.
- A study with 30% power reports a significant result. Should that make you more or less confident in the size of the effect it reports, compared with a study at 90% power?
A way to think about it
With low power, only samples that happened to overestimate the effect cross the cutoff. Think about what the significant results from such studies have in common.
- The effect you care about is half as large as you first assumed. By what factor does the required sample size change, and why is the relation not linear?
A way to think about it
Look at where sits in the sample size formula. The standard error falls with the square root of .
- Which error is worse depends on the setting. Give one case where a Type II error is the more costly one and say how you would set there.
A way to think about it
Think of a cheap screening test for a serious condition, where a false alarm leads only to a follow-up test but a miss leaves the condition untreated.