1. Home
  2. Explore
  3. Mathematics
  4. Hypothesis Testing Framework

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Hypothesis Testing Framework

Hypothesis Testing: The Universal Algorithm

Hypothesis testing is a universal algorithm that powers A/B tests, clinical trials, quantitative trading, and nearly every data-driven decision. The core idea is a simple four‑step function: take data → produce a decision. The underlying logic never changes—only the specific formula used in one of the steps changes depending on the type of data.


The Language of Hypothesis Testing

Before diving into the algorithm, four key terms define every hypothesis test:

  • Null hypothesis (H0H_0H0​): The boring status quo, the default reality that assumes no effect or difference.

  • Alternative hypothesis (H1H_1H1​): The exciting new theory you want to prove—the presence of an effect or difference.

  • Alpha (α\alphaα): The BS threshold—the maximum risk you're willing to take of being wrong (usually set at 0.05).

  • P‑value (ppp): The probability of observing data as extreme as yours, assuming the null hypothesis is true.

The universal rule: If p<αp < \alphap<α, reject H0H_0H0​. If p≥αp \geq \alphap≥α, fail to reject H0H_0H0​.


The Four‑Step Algorithm

Step 1: Formulate

Define the null hypothesis (H0H_0H0​) and the alternative hypothesis (H1H_1H1​).

Step 2: Calibrate

Set the significance level α\alphaα (e.g., 0.05). This answers: How much evidence do I need?

Step 3: Compute

Calculate a test statistic that measures how far the observed data is from what H0H_0H0​ predicts. The formula depends on the data type.

Step 4: Decide

Compare the p‑value (derived from the test statistic) with α\alphaα. If p<αp < \alphap<α, reject H0H_0H0​; otherwise, fail to reject H0H_0H0​ (the status quo remains).


Example 1: The Rigged Coin (Intuition Built from Scratch)

The Scenario

A friend claims a coin is fair (50 % heads, 50 % tails). You flip it 10 times and get 9 heads and 1 tail. Is your friend cheating, or is this just bad luck?

The Intuitive Logic

  1. Assume the coin is fair (this is H0H_0H0​).

  2. Calculate the probability of getting a result this extreme (9 or 10 heads) purely by chance.

  3. If that probability is very low (below a BS threshold), call BS—reject fairness.

The Math

  • Probability of exactly 10 heads: (0.5)10≈0.0009766(0.5)^{10} \approx 0.0009766(0.5)10≈0.0009766.

  • Probability of exactly 9 heads: 10×(0.5)10≈0.009765610 \times (0.5)^{10} \approx 0.009765610×(0.5)10≈0.0097656.

  • Total probability of 9 or more heads = 0.0009766+0.0097656=0.0107422≈1.07 %0.0009766 + 0.0097656 = 0.0107422 \approx 1.07 \%0.0009766+0.0097656=0.0107422≈1.07 %.

So the p‑value is 0.0107. With a BS threshold (alpha) of 0.05, 0.0107<0.050.0107 < 0.050.0107<0.05. Therefore, reject H0H_0H0​—the coin is rigged.

The Rosetta Stone: Intuition → Formal Terms

Intuitive Idea

Formal Name

Symbol

“Assume the coin is fair”

Null hypothesis

H0H_0H0​

“Your friend is cheating”

Alternative hypothesis

H1H_1H1​

1.07 % chance

P‑value

ppp

5 % BS threshold

Significance level

α\alphaα

Key visualization: The outcomes can be plotted on a bar chart. The bars for 9 or 10 heads are tiny tails—this is the rejection region. If the observed outcome falls there, you reject H0H_0H0​.

Implementation in Python

from scipy.stats import binom_test

k = 9       # successes (heads)
n = 10      # total flips
p = 0.5     # null probability
p_value = binom_test(k, n, p, alternative='greater')
print(p_value)   # 0.0107421875

From Discrete to Continuous Data: The Need for a Universal Yardstick

Coin flips produce discrete data (countable). But business data like revenue, time on site, or weight are continuous—you cannot count them. For continuous data, the Z‑test becomes the standard tool, underpinned by the Central Limit Theorem.


Example 2: The Chip Factory (Z‑Test)

The Setup

A factory produces potato chips; target weight per bag is 100 g. From historical data, the machine’s standard deviation (σ\sigmaσ) is 5 g. A sample of 50 bags shows a sample mean (xˉ\bar{x}xˉ) of 102 g. Is the machine broken (making heavier bags) or is the 2 g difference just random noise?

The Central Limit Theorem (CLT)

The Central Limit Theorem promises that, regardless of the shape of the population distribution, the distribution of sample means becomes approximately normal (bell‑shaped) for large enough sample sizes. This justifies using a Z‑test.

The Z‑Score Formula

Z=signalnoise=xˉ−μσ/nZ = \frac{\text{signal}}{\text{noise}} = \frac{\bar{x} - \mu}{\sigma / \sqrt{n}}Z=noisesignal​=σ/n​xˉ−μ​
  • Signal: xˉ−μ\bar{x} - \muxˉ−μ (how far from the target)

  • Noise (standard error): σ/n\sigma / \sqrt{n}σ/n​ (how much variation is normal for that sample size)

Applying the Four Steps

  1. Formulate: H0:μ=100H_0: \mu = 100H0​:μ=100 (machine is fine), H1:μ≠100H_1: \mu \neq 100H1​:μ=100 (machine is broken).

  2. Calibrate: α=0.05\alpha = 0.05α=0.05.

  3. Compute:

    • Signal = 102−100=2102 - 100 = 2102−100=2.

    • Noise = 5/50≈0.7075 / \sqrt{50} \approx 0.7075/50​≈0.707.

    • Z=2/0.707≈2.83Z = 2 / 0.707 \approx 2.83Z=2/0.707≈2.83.

  4. Decide: A Z‑score of 2.83 corresponds to a p‑value of approximately 0.0047. Since 0.0047<0.050.0047 < 0.050.0047<0.05, reject H0H_0H0​—the machine is broken.

Visualizing the Z‑Score

A Z‑score of 2.83 lies far in the tail of the standard normal distribution—deep in the “very unlikely under H0H_0H0​” zone.

Python Implementation

from scipy.stats import norm
import numpy as np

mu = 100
sigma = 5
n = 50
x_bar = 102

signal = x_bar - mu
noise = sigma / np.sqrt(n)
z = signal / noise
p_value = 2 * (1 - norm.cdf(abs(z)))   # two‑tailed test

print(f"Z = {z:.3f}")      # Z = 2.828
print(f"p = {p_value:.4f}") # p = 0.0047

The Flaw of the Z‑Test: Unknown Population Standard Deviation

The Z‑test assumes you know σ\sigmaσ—the population standard deviation. In real A/B tests, you never know σ\sigmaσ beforehand; you have to estimate it from the sample. That added uncertainty requires a different tool: the ttt‑test.


Example 3: The New Button (Two‑Sample ttt‑Test)

The Setup

Goal: increase time on site. Group A (old button) has 10 users, mean = 45 s, sample standard deviation = 15 s. Group B (new button) has 10 users, mean = 55 s, sample standard deviation = 15 s. Is the +10 s improvement real or random noise?

The ttt‑Statistic

t=signalnoise=xˉB−xˉAsA2nA+sB2nBt = \frac{\text{signal}}{\text{noise}} = \frac{\bar{x}_B - \bar{x}_A}{\sqrt{\frac{s_A^2}{n_A} + \frac{s_B^2}{n_B}}}t=noisesignal​=nA​sA2​​+nB​sB2​​​xˉB​−xˉA​​
  • Signal: difference in sample means

  • Noise: combined standard error (using sample standard deviations sss instead of population σ\sigmaσ)

Applying the Four Steps

  1. Formulate: H0H_0H0​: new button does nothing (difference = 0). H1H_1H1​: new button works (difference ≠ 0).

  2. Calibrate: α=0.05\alpha = 0.05α=0.05.

  3. Compute:

    • Signal = 55 – 45 = 10.

    • Noise = 152/10+152/10=22.5+22.5=45≈6.71\sqrt{15^2/10 + 15^2/10} = \sqrt{22.5 + 22.5} = \sqrt{45} \approx 6.71152/10+152/10​=22.5+22.5​=45​≈6.71.

    • t=10/6.71≈1.49t = 10 / 6.71 \approx 1.49t=10/6.71≈1.49.

  4. Decide: A t‑score of 1.49 (with approximately 18 degrees of freedom) gives a p‑value of about 0.15. Since 0.15≥0.050.15 \geq 0.050.15≥0.05, fail to reject H0H_0H0​—the 10‑second improvement is likely just random noise.

Why Did the Test Fail?

The noise (6.71 s) was almost as large as the signal (10 s). Small sample sizes (n=10n=10n=10) produce massive noise.

Two Levers to Win

  • Increase signal: Make a much bigger improvement.

  • Increase sample size (nnn): The most common approach. More data shrinks the noise term because it divides by n\sqrt{n}n​.

Python Implementation

from scipy.stats import ttest_ind

group_a = [...]  # list of 10 observed times
group_b = [...]  # list of 10 observed times
t_stat, p_value = ttest_ind(group_a, group_b)

print(f"t = {t_stat:.2f}")    # e.g., t = 2.29
print(f"p = {p_value:.4f}")   # e.g., p = 0.0342

With a different dataset (p = 0.0342 < 0.05), the test would succeed.


Example 4: The Red Button (Chi‑Square Test for Categorical Data)

The ttt‑test works for continuous variables (time, weight, money). But what about clicks? Yes/no (binary) data is categorical. For that, the chi‑square (χ2\chi^2χ2) test is used.

The Setup

100 visitors each see a blue button (A) or a red button (B). Blue: 10 sales (10 % conversion). Red: 20 sales (20 % conversion). Is red truly better, or is it a lucky fluke?

Mental Model: Observed vs. Expected

  • Observed (OOO): what actually happened (raw data)

  • Expected (EEE): what would happen if H0H_0H0​ were true (no difference between groups)

If the gap between OOO and EEE is large → real effect. If small → noise.

χ2\chi^2χ2 Formula

χ2=∑(O−E)2E\chi^2 = \sum \frac{(O - E)^2}{E}χ2=∑E(O−E)2​
  • Difference O−EO - EO−E is squared to make errors positive and penalize big deviations.

  • Dividing by EEE normalizes: a difference of 5 is huge if E=10E=10E=10, but trivial if E=10 000E=10\,000E=10000.

Applying the Four Steps

  1. Formulate: H0H_0H0​: color doesn’t matter (conversion rate is the same). H1H_1H1​: color matters.

  2. Build the observed table (2 × 2):

    Group

    Bought

    Did Not Buy

    Blue

    10

    90

    Red

    20

    80

  3. Build the expected table under H0H_0H0​: Overall conversion rate = 30/200 = 15 %. So expect 15 % of each group to buy:

    • Blue expected bought = 15, not bought = 85.

    • Red expected bought = 15, not bought = 85.

  4. Compute χ2\chi^2χ2:

    • Blue bought: (10−15)2/15=1.6667(10-15)^2/15 = 1.6667(10−15)2/15=1.6667

    • Blue not bought: (90−85)2/85≈0.2941(90-85)^2/85 \approx 0.2941(90−85)2/85≈0.2941

    • Red bought: (20−15)2/15=1.6667(20-15)^2/15 = 1.6667(20−15)2/15=1.6667

    • Red not bought: (80−85)2/85≈0.2941(80-85)^2/85 \approx 0.2941(80−85)2/85≈0.2941

    • Sum: χ2≈3.92\chi^2 \approx 3.92χ2≈3.92

    This gives a p‑value of approximately 0.0477.

  5. Decide: 0.0477<0.050.0477 < 0.050.0477<0.05 → reject H0H_0H0​ → the red button really is better (just barely).

Reality Check: One Sale Changes Everything

If red had gotten 19 sales instead of 20, the p‑value jumps to 0.0763 (not significant). Categorical data is low‑resolution; a single observation can flip the decision. Therefore, categorical tests require huge sample sizes for reliable conclusions.

Python Implementation

from scipy.stats import chi2_contingency

observed = [[10, 90],
            [20, 80]]

chi2, p_value, dof, expected = chi2_contingency(observed)

print(f"χ² = {chi2:.2f}")   # 3.92
print(f"p = {p_value:.4f}") # 0.0477

The Decision Matrix: Which Test to Use?

Data Type

Question

Tool (when sss unknown)

Rarely Used

Categorical (yes/no, clicks)

“Is the conversion rate different?”

χ2\chi^2χ2 test

–

Continuous (time, revenue)

“Is the average different?” (don’t know σ\sigmaσ)

Two‑sample ttt‑test

–

Continuous (manufacturing, science)

“Is the average off‑target?” (know σ\sigmaσ)

–

One‑sample ZZZ‑test

Your job is not to be a human calculator. Your job is decision‑making. Know which tool matches your data and question.


Production Pitfall #1: P‑Hacking

P‑hacking is the temptation to peek at results repeatedly and stop the test as soon as p<0.05p < 0.05p<0.05. P‑values bounce randomly, especially early on. Peeking invalidates the statistics by inflating the chance of a false positive.

The Professional Solution

  1. Pre‑commit: Decide the sample size needed (e.g., 10,000 users) before the test starts.

  2. Run the test – do not touch the dashboard.

  3. No peeking – this is the cardinal sin of A/B testing.

  4. Decide once – check the p‑value only at the predetermined sample size.


Production Pitfall #2: The “Google Problem” – Statistical vs. Practical Significance

The Scenario

A tiny code change at Google scale (50 million users) yields a 0.001 s improvement in search speed. Because the sample size is astronomical, the p‑value is virtually 0 — the effect is statistically significant.

Two Kinds of Significance

  • Statistical significance: “Is the effect real?” – yes, the math is certain it’s not random noise.

  • Practical significance: “Does it matter?” – a 0.001 s improvement is invisible to humans and provides no real value.

The Production Rule

Always check two things before deciding:

  1. The p‑value → tells you if an effect actually exists (certainty).

  2. The effect size → tells you if the effect is big enough to care about (magnitude).

A tiny p‑value does not mean a big effect. It only means we are very sure that some effect exists, no matter how small.


Summary: The Universal Algorithm in Action

The four‑step algorithm is universal:

  1. Formulate H0H_0H0​ and H1H_1H1​

  2. Set α\alphaα

  3. Compute the test statistic (the only part that changes with data type)

  4. Compare p‑value to α\alphaα and decide

The tests covered (binomial, ZZZ, ttt, χ2\chi^2χ2) are all variations on this single framework. Once the logic is internalized, any new test is just a matter of plugging in the correct formula.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent