Sign in

Tailed tests

One-tailed and two-tailed tests

The choice of whether a test counts extreme results in one direction only or in both, which sets where the rejection region sits and how the p-value is computed.

Overview

A test rejects the null hypothesis when the statistic lands in a region that would be rare if the null were true. The alternative hypothesis decides where that region goes. If you only care whether a parameter is larger, the whole rare region goes in the right tail: a right-tailed test. If only smaller matters, it goes in the left tail. If any difference matters, the region is split between both tails: a two-tailed test. Putting all of α\alpha on one side moves the cutoff closer to zero, so a one-tailed test detects an effect in its chosen direction more easily. The price is that it can never detect an effect in the other direction.

A short history

The distinction follows from the Neyman and Pearson framework of 1933, in which the alternative hypothesis determines where the rejection region lies: in one tail if only one direction counts, in both if either does. Fisher's early tables and examples were mostly two sided. Since the mid twentieth century statisticians have debated when a one sided test is legitimate, and the usual advice is that the direction must be fixed before the data are seen.

How it works

  1. Decide from the question, before seeing data, whether the alternative is 'smaller', 'larger' or 'different'.
  2. Compute the test statistic, a zz or a tt value.
  3. Left-tailed: the p-value is the probability of a statistic at or below the observed one.
  4. Right-tailed: the p-value is the probability of a statistic at or above the observed one.
  5. Two-tailed: the p-value is twice the smaller of those two probabilities.
  6. Reject when the p-value is below α\alpha, which is the same as the statistic falling in the matching rejection region.

Watch out for

  • Picking the tail after seeing which way the data point makes the real false positive rate 2α2\alpha, because either direction would have been declared significant.
  • A one-tailed test has no power against an effect in the opposite direction, so a large harmful effect will be reported as nothing found.
  • A result that is significant one-tailed but not two-tailed is weak evidence, and readers will rightly ask whether the direction was fixed in advance.
  • With distribution: t the template's power uses tt cutoffs with a normal approximation for the shifted statistic, so it is slightly off for small degrees of freedom.

Use cases

When to use it

Framing any z or t test. Use two tails unless an effect in one direction is impossible or would lead to exactly the same action as no effect.

In industry

Pharmaceutical development
Non inferiority trials use a one sided test to show that a new drug is not worse than the standard by more than a set margin.
Quality control
A manufacturer tests only whether the defect rate exceeds the allowed limit, since a lower rate needs no action.
Scientific publishing
Most journals expect two sided tests by default, because an effect in the unexpected direction would also matter.

Choosing it: what must hold

  • A direction for the alternative hypothesis decided before the data are collected.
  • For a one tailed test, a sound reason why an effect in the other direction would be treated the same as no effect.
  • A symmetric statistic such as z or t; chi-square and F tests of fit are upper tailed by construction.

When to choose something else

IfUse instead
You have no firm prior direction or the opposite effect would matterA two-tailed test
You want to show two treatments are practically the sameAn equivalence test with two one sided tests
You are tempted to choose the tail after seeing the dataKeep the two-tailed test; switching inflates the Type I error rate

Math foundations

  1. The three alternatives

    H0: θ=θ0H1left: θ<θ0,H1right: θ>θ0,H1two: θ≠θ0H_0:\ \theta = \theta_0 \qquad H_1^{\text{left}}:\ \theta < \theta_0, \quad H_1^{\text{right}}:\ \theta > \theta_0, \quad H_1^{\text{two}}:\ \theta \ne \theta_0

    The null is the same in all three cases. Only the alternative changes, and with it the direction that counts as evidence.

  2. The three p-values

    pleft=F(t),pright=1−F(t),ptwo=min⁡{1, 2min⁡(pleft, pright)}p_{\text{left}} = F(t), \qquad p_{\text{right}} = 1-F(t), \qquad p_{\text{two}} = \min\{1,\ 2\min(p_{\text{left}},\,p_{\text{right}})\}

    FF is the cumulative distribution of the statistic under the null. The left and right p-values always add to 1, so if one is small the other is large. The two-tailed value is twice the smaller one.

  3. The rejection regions

    left: t<qα,right: t>q1−α,two: ∣t∣>q1−α/2\text{left: } t < q_{\alpha}, \qquad \text{right: } t > q_{1-\alpha}, \qquad \text{two: } \lvert t\rvert > q_{1-\alpha/2}

    Each region has probability α\alpha under the null. Because q1−α<q1−α/2q_{1-\alpha} < q_{1-\alpha/2}, the one-tailed cutoff is nearer to zero: 1.645 against 1.96 for a zz test at 5%.

  4. Power of the z test

    power(δ)=Φ(ℓ−δ)+Φ(δ−u)\text{power}(\delta) = \Phi(\ell-\delta) + \Phi(\delta-u)

    The probability of rejecting when the statistic is centred at δ\delta instead of 0, where ℓ\ell and uu are the lower and upper cutoffs (minus or plus infinity when a side is unused, which makes that term zero). At δ=0\delta = 0 it equals α\alpha.

Symbols

θ, θ0\theta,\ \theta_0
the parameter and the value the null claims
tt
the observed test statistic
FF
cumulative distribution function of the statistic under the null
quq_u
quantile of the null distribution at probability u
α\alpha
significance level
δ\delta
true effect in standard-error units, the shift argument in the template
ℓ, u\ell,\ u
lower and upper cutoffs of the rejection region
Φ\Phi
standard normal cumulative distribution function

Worked by hand

A zz statistic of 1.801.80 at α=0.05\alpha = 0.05. The normal table gives Φ(1.80)=0.9641\Phi(1.80) = 0.9641.

pleft=0.9641p_{\text{left}} = 0.9641
pright=1−0.9641=0.0359p_{\text{right}} = 1-0.9641 = 0.0359
ptwo=2×0.0359=0.0719p_{\text{two}} = 2 \times 0.0359 = 0.0719
1.645<1.80<1.961.645 < 1.80 < 1.96

The right-tailed test rejects (0.0359<0.050.0359 < 0.05), the two-tailed test does not (0.0719>0.050.0719 > 0.05), and the left-tailed test is nowhere near. The same data give three answers, which is why the tail must be fixed first.

Visual example

Loading the example.

Try this

  • Leave the statistic at 1.8: the right-tailed test rejects and the two-tailed test does not.
  • Drag the statistic to -1.8 and see which test rejects now.
  • Switch to Student's t with 2 degrees of freedom and watch the cutoffs move outward.

Code sample

from impl import TailedTest
from config import TailedTestsConfig

test = TailedTest(TailedTestsConfig(alpha=0.05, distribution="z"))
print(test.p_values(1.8))        # left 0.964, right 0.036, two 0.072
print(test.decisions(1.8))       # only the right-tailed test rejects
print(test.power(2.5, "right"), test.power(2.5, "two"))
Read the implementation (173 lines)
"""One-tailed against two-tailed tests for a z or t statistic.

NumPy and the standard library only. Normal and Student t distribution functions and quantiles are computed
in this file (the t distribution through the regularized incomplete beta function).
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import TailedTestsConfig
except ImportError:  # run from the template's own folder
    from config import TailedTestsConfig

TAILS = ("left", "right", "two")

def _betacf(a: float, b: float, x: float) -> float:
    """Continued fraction of the incomplete beta function (modified Lentz method)."""
    tiny = 1e-300
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    d = 1.0 / (d if abs(d) > tiny else tiny)
    h = d
    for m in range(1, 2000):
        m2 = 2 * m
        for aa in (
            m * (b - m) * x / ((qam + m2) * (a + m2)),
            -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)),
        ):
            d = 1.0 + aa * d
            d = 1.0 / (d if abs(d) > tiny else tiny)
            c = 1.0 + aa / c
            c = c if abs(c) > tiny else tiny
            delta = d * c
            h *= delta
        if abs(delta - 1.0) < 1e-15:
            break
    return h


def betainc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b), for a, b > 0 and 0 <= x <= 1."""
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        return front * _betacf(a, b, x) / a
    return 1.0 - front * _betacf(b, a, 1.0 - x) / b

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 t_cdf(t: float, df: float) -> float:
    """P(T <= t) for Student's t with `df` degrees of freedom."""
    tail = 0.5 * betainc(0.5 * df, 0.5, df / (df + t * t))
    return 1.0 - tail if t > 0 else tail


def t_sf(t: float, df: float) -> float:
    """P(T > t) for Student's t with `df` degrees of freedom."""
    return t_cdf(-t, df)

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)

def t_ppf(p: float, df: float) -> float:
    """Quantile of Student's t: the t with P(T <= t) = 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 -t_ppf(1.0 - p, df)
    lo = -1.0
    while t_cdf(lo, df) > p:
        lo *= 2.0
    return _bisect(lambda t: t_cdf(t, df) - p, lo, 0.0)

class TailedTest:
    """Compares the left-tailed, right-tailed and two-tailed versions of one test."""

    def __init__(self, config: TailedTestsConfig | None = None) -> None:
        self.config = config or TailedTestsConfig()

    def _cdf(self, x: float) -> float:
        return norm_cdf(x) if self.config.distribution == "z" else t_cdf(x, self.config.df)

    def _ppf(self, p: float) -> float:
        return norm_ppf(p) if self.config.distribution == "z" else t_ppf(p, self.config.df)

    def p_values(self, statistic: float) -> dict:
        """p-value of the statistic under each alternative.

        `left`:  H1 says the parameter is smaller, p = P(T <= statistic).
        `right`: H1 says the parameter is larger,  p = P(T >= statistic).
        `two`:   H1 says the parameter differs,    p = 2 * min(left, right).
        """
        left, right = self._cdf(statistic), self._cdf(-statistic)
        return {"left": left, "right": right, "two": min(1.0, 2.0 * min(left, right))}

    def rejection_region(self, tail: str) -> tuple[float, float]:
        """(lower, upper): the test rejects when the statistic is below `lower` or above `upper`.

        tail: "left", "right" or "two". A one-tailed test puts all of alpha in one tail, so its cutoff
        is closer to zero than the two-tailed cutoff, which splits alpha in half.
        """
        if tail not in TAILS:
            raise ValueError(f"tail must be one of {TAILS}, got {tail!r}")
        a = self.config.alpha
        if tail == "left":
            return self._ppf(a), math.inf
        if tail == "right":
            return -math.inf, self._ppf(1.0 - a)
        upper = self._ppf(1.0 - a / 2.0)
        return -upper, upper

    def decisions(self, statistic: float) -> dict:
        """For each tail: True when that version of the test rejects the null hypothesis."""
        return {tail: p < self.config.alpha for tail, p in self.p_values(statistic).items()}

    def power(self, shift: float, tail: str) -> float:
        """Probability of rejecting when the z statistic is centred at `shift` instead of 0.

        shift: true effect in standard-error units, (true mean - null mean) / (sigma / sqrt(n)).
        Exact for the z test; with `distribution: t` the cutoffs are t cutoffs and the result is the
        normal approximation to the power.
        """
        lower, upper = self.rejection_region(tail)
        return norm_cdf(lower - shift) + norm_cdf(shift - upper)

    def simulate(self, shift: float, n: int = 16, trials: int = 5000, seed: int = 0) -> dict:
        """Rejection rate of each version on simulated samples of size n with true mean shift / sqrt(n).

        Uses a z statistic with known standard deviation 1 (`distribution: z`) or a t statistic with
        the sample standard deviation (`distribution: t`, which needs df = n - 1).
        """
        if self.config.distribution == "t" and abs(self.config.df - (n - 1)) > 1e-9:
            raise ValueError("for the t statistic, df must equal n - 1")
        rng = np.random.default_rng(seed)
        x = rng.normal(shift / math.sqrt(n), 1.0, size=(trials, n))
        scale = 1.0 if self.config.distribution == "z" else x.std(axis=1, ddof=1)
        stats = x.mean(axis=1) / (scale / math.sqrt(n))
        out = {}
        for tail in TAILS:
            lower, upper = self.rejection_region(tail)
            out[tail] = float(np.mean((stats < lower) | (stats > upper)))
        return out
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

With TailedTest() call p_values(1.8) and decisions(1.8) and check the worked example. Print rejection_region for each tail. Then compare power(2.0, "right"), power(2.0, "two") and power(-2.0, "right"), and confirm them with simulate(2.0) and simulate(-2.0).

Check on learning

  1. A new drug is tested right-tailed for 'better than placebo'. The data show it is clearly worse, with z=−3z = -3. What does the test report, and is that acceptable?
    A way to think about it

    Compute the right-tailed p-value at z=−3z = -3. Then ask whether 'harmful' and 'no different' would lead to the same decision in practice.

  2. For a true shift of 2 standard errors, the right-tailed test has power about 0.64 and the two-tailed about 0.52. Where does the extra power come from, and what was traded for it?
    A way to think about it

    Compare the cutoffs each test uses on the right side, then look at each test's power when the shift is −2-2.

  3. An analyst always runs both one-tailed tests and reports the significant one at α=0.05\alpha = 0.05. What is the true false positive rate of this habit?
    A way to think about it

    Under the null, find the probability that the statistic falls in either one-tailed rejection region.

  4. Why do the left and right p-values of a continuous statistic always add to 1, and what does that imply when one of them is 0.5?
    A way to think about it

    Together the two tails at the observed value cover the whole distribution. A value of 0.5 puts the statistic at the median of the null distribution.