9.3. Hypotheses and p-Values#
In Assessing a Model with Simulation you checked whether promotions followed a random-selection model. In Comparing Distributions you compared a survey’s age mix with the customer base. Both times you did the same four things: you stated a chance model, chose a number to measure disagreement with it, simulated that number many times, and compared the real data with the simulation. This section gives those four steps their standard names, applies them to a new case, and then covers what a test result means: the p-value, the cutoffs used to decide, the two ways a decision can be wrong, and why a statistically significant result is not always a useful one.
9.3.1. The Four Steps of a Test#
A hypothesis test is a way to decide whether data are consistent with a stated chance model. Every test in this book follows four steps.
Hypotheses. State the null hypothesis, the chance model whose predictions you will check, and the alternative hypothesis, the competing claim that the data may support.
Test statistic. Choose a single number computed from the data that is large (or small) when the data disagree with the null hypothesis in the way the alternative describes.
Null distribution. Find the values the statistic takes when the null hypothesis is true, usually by simulating the model many times.
Conclusion. Compare the observed statistic with the null distribution. Decide whether the data are consistent with the null hypothesis or whether they are evidence against it.
The two earlier sections already followed these steps, without the names:
Step |
9.1: Promotions |
9.2: Survey |
9.3: Traffic split |
|---|---|---|---|
1. Hypotheses |
Promotions are random draws; 40% women |
Respondents are a random sample of customers |
Each visitor is equally likely to see A or B |
2. Test statistic |
Number of women promoted |
Total variation distance |
Distance of the observed percent from 50 |
3. Null distribution |
10,000 simulated rounds of 50 promotions |
10,000 simulated samples of 600 |
10,000 simulated splits of 8,000 visitors |
4. Conclusion |
11 is far in the low tail: evidence against |
0.15 is far above every simulated value: evidence against |
The observed distance is typical: no evidence against |
9.3.1.1. Practice#
### Exercise: Put the Four Steps in Order
# A support manager claims that half of all tickets are resolved on first
# contact. In a random sample of 200 tickets, 118 were. The four statements
# below describe a test of the claim, but they are out of order.
# 1. Put the letters in the order of the four steps: hypotheses, test
# statistic, null distribution, conclusion.
# 2. Print the letters, separated by spaces.
# Print exactly:
# B D A C
steps = {
'A': 'Simulate 10,000 samples of 200 tickets, each resolved with probability 0.5, and record the count each time.',
'B': 'Each ticket is resolved on first contact with probability 0.5.',
'C': 'See where 118 falls among the simulated counts and decide.',
'D': 'Use the number of tickets resolved on first contact out of 200.',
}
### Your code starts here.
### Your code ends here.
B D A C
9.3.2. Case: Checking a Traffic Split#
Fig. 9.1 is an example of A/B testing: a company shows version A of a page or screen to some users and version B to others, then compares how each group behaves to learn which version works better. It is used in, for example, conversion rate optimization (CRO), which changes a page to influence user behavior so that more users buy, sign up, or take some other desired action. In the figure, the two versions of an app screen differ in the layout of the top and bottom bars.
Fig. 9.1 Two versions of an app screen shown to different users (illustration)#
An online store runs an A/B test on its product page. The testing tool is set to send each visitor to version A or version B of the page with equal chance. Assigning units, here visitors, to groups by chance is called random assignment. Over the first week, 8,000 visitors entered the test, and 4,034 of them saw version B. (The store and its numbers are hypothetical, made up for this example.)
That is 50.425% of visitors, a little above half. Is the tool working as designed? This matters because a split that is far from 50/50 usually signals a bug, such as a page that loads slowly for one version so that visitors leave before they are counted. Analysts call this a sample ratio mismatch. If it happens, the two groups differ in more than the page design, and the test’s comparison of purchases cannot be trusted. Chapter 10 returns to A/B tests; here you only check the split.
Some difference from exactly 50% is expected. A fair coin does not give exactly half heads in 8,000 flips. The question is whether 4,034 out of 8,000 is the kind of difference chance produces.
n_visitors = 8000
saw_b = 4034
print('Percent who saw version B:', round(100 * saw_b / n_visitors, 3))
Percent who saw version B: 50.425
9.3.2.1. Step 1: The Hypotheses#
The null hypothesis says that the tool is fair: each visitor independently has a 50% chance of being sent to version B, and any gap from 50% is due to chance. The alternative hypothesis says that the tool is not fair: the chance of being sent to B is not 50%.
Null hypothesis: each visitor has a 50% chance of seeing version B, independently of the others. Alternative hypothesis: the chance of seeing version B is not 50%.
The alternative here points in both directions. A tool that sends too many visitors to B is broken, and so is a tool that sends too few. A test whose alternative allows differences in either direction is a two-sided test.
Other questions care about only one direction. Suppose a supplier claims that at most 2% of its parts are defective, and a buyer inspects 500 parts. Finding fewer defects than claimed is good news and needs no action. Only too many defects count against the claim. A test whose alternative points in one direction is a one-sided test.
Question |
Null hypothesis |
Alternative hypothesis |
Test |
|---|---|---|---|
Is the traffic split fair? |
The chance of seeing B is 50%. |
The chance of seeing B is not 50%. |
Two-sided |
Is the supplier’s claim true? |
At most 2% of parts are defective. |
More than 2% of parts are defective. |
One-sided |
The direction comes from the business question, not from the data. Choose it before looking at the data. Switching to a one-sided test after seeing which way the gap points makes the evidence look stronger than it is. Step 4 shows by how much.
9.3.2.2. Step 2: The Test Statistic#
The test statistic must measure disagreement with the null hypothesis in a way that fits the alternative. Because a surplus of B visitors and a shortage of B visitors are both problems, the statistic for this two-sided test ignores the direction of the gap. It is the distance of the percent who saw B from 50, in percentage points:
The statistic computed from the real data is the observed statistic.
def split_distance(count_b, n=8000):
# Distance, in percentage points, of the percent who saw B from 50
return np.abs(100 * count_b / n - 50)
observed_distance = split_distance(saw_b)
print('Observed distance (percentage points):', round(observed_distance, 3))
Observed distance (percentage points): 0.425
A one-sided test needs a statistic that keeps the sign of the gap. For the supplier, it is the defect percent minus 2, in percentage points:
Only large positive values count against the claim. A shipment with 1% defective gives a gap of -1, which is good news. With an absolute value, that good news would count against the supplier as strongly as a shipment with 3% defective. Keeping the sign is what makes the supplier statistic one-sided, and dropping it is what makes the traffic-split statistic two-sided.
9.3.2.3. Step 3: The Null Distribution#
If the tool is fair, the number of visitors who see B in a week is the result of 8,000 independent draws, each with a 50% chance. This is a binomial count, as in Sampling Variability. Simulate it with rng.binomial. One simulated week:
rng = np.random.default_rng(4)
one_week = rng.binomial(n_visitors, 0.5)
print('Visitors who saw B in one simulated fair week:', one_week)
print('Distance:', round(split_distance(one_week), 3))
Visitors who saw B in one simulated fair week: 4042
Distance: 0.525
Now repeat for 10,000 simulated fair weeks. The collection of 10,000 distances approximates the null distribution of the statistic: the values it takes when the null hypothesis is true.
simulated_counts = rng.binomial(n_visitors, 0.5, size=10000)
simulated_distances = split_distance(simulated_counts)
print('Number of simulated weeks:', len(simulated_distances))
print('Mean simulated distance:', round(np.mean(simulated_distances), 3))
print('Largest simulated distance:', round(np.max(simulated_distances), 3))
fig, ax = plt.subplots(figsize=(7, 3.8))
ax.hist(simulated_distances, bins=np.arange(0, 2.4, 0.1), color='lightsteelblue',
edgecolor='white')
ax.scatter([observed_distance], [0], color='crimson', s=90, zorder=3,
clip_on=False, label='Observed: 0.425')
ax.set_xlabel('Distance from 50% (percentage points)')
ax.set_ylabel('Simulated weeks')
ax.set_title('A fair 50/50 tool often lands this far from half')
ax.legend()
plt.show()
Number of simulated weeks: 10000
Mean simulated distance: 0.451
Largest simulated distance: 2.188
9.3.2.4. Step 4: The Conclusion#
Look at where the observed distance falls. The red dot sits in the middle of the bulk of the simulated distances, not out in the tail. To be specific, count the share of simulated weeks whose distance is at least as large as the observed 0.425.
at_least_as_far = simulated_distances >= observed_distance
print('Weeks at least as far from 50% as observed:', np.sum(at_least_as_far))
print('Share of simulated weeks:', np.mean(at_least_as_far))
Weeks at least as far from 50% as observed: 4590
Share of simulated weeks: 0.459
About 46% of fair weeks are at least as far from 50% as the observed week. A gap like this one is ordinary for a fair tool. The data are consistent with the null hypothesis. This is not proof that the tool is fair: the test only shows that the data give no reason to doubt it. The traffic split looks fine, and the analyst can go on to compare purchases between the versions.
Because the test is two-sided, a week counts as “at least as far” from 50% when its gap goes in either direction: at least 0.425 points above 50%, or at least 0.425 points below it. The plot below keeps the sign of each simulated gap, so the two tails show separately.
signed_gaps = 100 * simulated_counts / n_visitors - 50
observed_gap = 100 * saw_b / n_visitors - 50
upper_tail = signed_gaps >= observed_gap
lower_tail = signed_gaps <= -observed_gap
print('Share in the upper tail (B above 50%):', np.mean(upper_tail))
print('Share in the lower tail (B below 50%):', np.mean(lower_tail))
print('Share in both tails: ', np.mean(upper_tail | lower_tail))
fig, ax = plt.subplots(figsize=(7, 3.8))
# Gaps move in steps of 0.0125 points; shift the bin edges off those steps.
bins = np.arange(-2.25, 2.3, 0.1) + 0.00625
ax.hist(signed_gaps, bins=bins, color='lightsteelblue', edgecolor='white')
ax.hist(signed_gaps[upper_tail | lower_tail], bins=bins, color='crimson',
edgecolor='white', label='At least 0.425 points from 50%')
ax.axvline(observed_gap, color='crimson', lw=2)
ax.axvline(-observed_gap, color='crimson', lw=2, ls='--')
ax.set_xlabel('Percent who saw B minus 50 (percentage points)')
ax.set_ylabel('Simulated weeks')
ax.set_title('A two-sided test counts both tails')
ax.legend()
plt.show()
Share in the upper tail (B above 50%): 0.2271
Share in the lower tail (B below 50%): 0.2319
Share in both tails: 0.459
The two tails hold about the same share, and together they make up the 46%. Now suppose the analyst had not chosen the direction in advance. Seeing that B got slightly more than half, the analyst switches to a one-sided alternative, “the tool favors B,” and counts only the upper tail. The share drops to about 23%, roughly half, although the data have not changed. For a result near the cutoff of the next section, that switch can turn an ordinary result into an apparently rare one. This is why the direction is chosen in Step 1, before the data are seen.
What would a rejection look like? Suppose the count of B visitors had been 4,104 instead, a distance of 1.3 percentage points. The same null distribution, with no new simulation, shows how rare that is.
hypothetical_distance = split_distance(4104)
print('Hypothetical distance:', round(hypothetical_distance, 3))
print('Share of simulated weeks at least this far:',
np.mean(simulated_distances >= hypothetical_distance))
fig, ax = plt.subplots(figsize=(7, 3.8))
bins = np.arange(0, 2.1, 0.1)
ax.hist(simulated_distances, bins=bins, color='lightsteelblue',
edgecolor='white')
tail = simulated_distances[simulated_distances >= hypothetical_distance]
ax.hist(tail, bins=bins, color='crimson', edgecolor='white')
ax.axvline(hypothetical_distance, color='crimson', lw=2)
ax.set_xlabel('Distance from 50% (percentage points)')
ax.set_ylabel('Simulated weeks')
ax.set_title('A 1.3-point gap would be rare for a fair tool')
plt.show()
Hypothetical distance: 1.3
Share of simulated weeks at least this far: 0.0231
Only about 2% of fair weeks reach a distance of 1.3 points. Such a result would be evidence against the null hypothesis, and the analyst would investigate the tool before trusting the test.
Rather than judging a result from where a dot sits on a graph, compute the share of simulated values in the tail and compare it with a cutoff chosen in advance. The cutoff is the subject of the next section.
9.3.2.5. Practice#
### Exercise: Check Another Traffic Split
# A second testing tool is also set to split visitors 50/50. In one week
# 6,000 visitors entered and 3,075 saw version B.
# 1. Compute the observed statistic: the distance, in percentage points,
# of the percent who saw B from 50.
# 2. Simulate 10,000 fair weeks with ex_rng.binomial(6000, 0.5, size=10000)
# and compute the distance for each.
# 3. Compute the share of simulated distances at least as large as the observed one.
# 4. Print the results, rounded as shown.
# Print exactly:
# Observed distance: 1.25
# Share at least as far: 0.0556
# Decision at 5%: do not reject the null
import numpy as np
ex_rng = np.random.default_rng(3)
ex_n = 6000
ex_saw_b = 3075
### Your code starts here.
### Your code ends here.
Observed distance: 1.25
Share at least as far: 0.0556
Decision at 5%: do not reject the null
9.3.3. The p-Value#
The share you computed in Step 4 has a standard name. The p-value is the probability, calculated assuming the null hypothesis is true, that the test statistic is at least as extreme as the observed statistic. “At least as extreme” means as far or farther in the direction or directions the alternative allows. In a simulation, the p-value is estimated by the share of simulated statistics at least as extreme as the observed one.
For the traffic split, the p-value is the share of fair weeks at least 0.425 points from 50%. The simulation gave about 0.46 (the exact binomial calculation gives about 0.45; simulation error accounts for the small difference). For the hypothetical distance of 1.3 points, it was about 0.02. A small p-value means the data would be surprising if the null hypothesis were true. A large p-value means they would not be.
p_value = np.mean(simulated_distances >= observed_distance)
p_value_hypothetical = np.mean(simulated_distances >= hypothetical_distance)
print('p-value, observed 0.425 points: ', p_value)
print('p-value, hypothetical 1.3 points:', p_value_hypothetical)
p-value, observed 0.425 points: 0.459
p-value, hypothetical 1.3 points: 0.0231
9.3.3.1. The Significance Level#
A significance level, often written as alpha, is a cutoff for a decision rule. Choose the null model, alternative, statistic, and cutoff before examining the test result. Then apply the rule consistently. For example, a rule might reject the null when the p-value is below 0.05.
Judgment remains important when choosing a defensible model, weighing the costs of errors, and deciding what action to take. It does not justify changing the cutoff after seeing a disappointing result. Report the statistic, p-value, assumptions, and limitations so readers can assess the evidence.
9.3.3.2. Conventions: 5% and 1%#
How small is “small”? According to the conventions:
With a significance level of 5%, reject the null if the p-value is below 0.05. This is called a statistically significant result at that level.
A p-value below 1% is sometimes labeled “highly statistically significant.” Report the actual p-value: this label does not measure the size or business value of an effect.
The hypothetical distance of 1.3 points has a p-value of about 0.02. That is below 0.05, so the result would be statistically significant at the 5% level, and the analyst would reject the null hypothesis that the tool is fair. It is not below 0.01, so it would not be called highly significant. The observed distance of 0.425 points has a p-value of about 0.46, far above 0.05. The analyst does not reject the null hypothesis. “Do not reject” is the careful wording: it says the evidence is insufficient, not that the null hypothesis has been shown true.
Significance level and observed significance level. The two terms are easy to confuse. The significance level is the cutoff you set in advance, such as 5%; it belongs to the decision rule and does not depend on the data. The p-value is computed from the data, which is why it is also called the observed significance level. The decision rule compares the two: reject the null when the observed significance level falls below the significance level.
9.3.3.3. Misreading the p-Value#
The p-value is a probability of results under the null model. It is not the probability that the null hypothesis is true, and it is not the probability that the result occurred “by chance.” A p-value of 0.46 does not mean the tool is fair with 46% probability. A large p-value means insufficient evidence to reject the model, rather than proof that it is correct. A small p-value does not say the effect is large or important, a point the last subsection returns to.
9.3.3.4. A Cutoff on the Statistic#
For a distance statistic, a 5% upper-tail rule can also be expressed using a high percentile of the null distribution. The pattern np.percentile(simulated_statistics, 95) finds an estimated 95th-percentile boundary: the value below which 95% of the simulated statistics fall, as in Descriptive Distributions. Compare the observed statistic with the unrounded boundary, and round only for display. With a small or discrete simulation, ties and percentile interpolation mean this need not agree exactly with a p-value rule.
Here is a deliberately small example.
# A small illustrative null distribution, sorted here for easy inspection.
import numpy as np
simulated_statistics = np.array([0.01, 0.02, 0.03, 0.04, 0.05,
0.06, 0.07, 0.08, 0.09, 0.10])
observed_distance_toy = 0.098
cutoff_value = np.percentile(simulated_statistics, 95)
print('95th percentile:', round(cutoff_value, 3))
print('Observed is above it:', observed_distance_toy > cutoff_value)
print('Tail fraction:', np.mean(simulated_statistics >= observed_distance_toy))
# The cutoff is 0.0955 before rounding. The tail fraction is 0.1 because
# ten repetitions allow proportions only in steps of 0.1. Use many more
# repetitions for an actual test, especially near a decision boundary.
# Here the two rules disagree: the observed value is above the 95th
# percentile, but the tail fraction 0.1 is not below 0.05.
95th percentile: 0.095
Observed is above it: True
Tail fraction: 0.1
With 10,000 repetitions the two rules agree. The 95th percentile of the simulated traffic-split distances is the distance that a fair tool exceeds only 5% of the time. An observed distance beyond it would be significant at the 5% level.
cutoff_95 = np.percentile(simulated_distances, 95)
print('95th percentile of simulated distances:', round(cutoff_95, 3))
print('Observed 0.425 above it:', observed_distance > cutoff_95)
print('Hypothetical 1.3 above it:', hypothetical_distance > cutoff_95)
95th percentile of simulated distances: 1.112
Observed 0.425 above it: False
Hypothetical 1.3 above it: True
For this tool, any week with a split more than about 1.1 points from 50% (below about 48.9% or above about 51.1%) would be flagged at the 5% level. The cutoff on the statistic and the cutoff on the p-value are two ways to state the same rule.
A short history of the p-value
The p-value as a measure of evidence comes from the British statistician Ronald Fisher, who developed it in the 1920s while analyzing agricultural experiments. He treated it as an informal gauge: the smaller the number, the stronger the reason to doubt the null hypothesis. He also suggested 5% as a convenient benchmark, not a law of nature.
In the 1930s Jerzy Neyman and Egon Pearson proposed a different framing. They asked how to choose a rule that makes a decision, fixed the acceptable rate of false alarms in advance, and introduced the alternative hypothesis and the two types of error described in the next section. Today’s textbook procedure combines the two ideas: a p-value computed from the data, compared with a cutoff chosen beforehand.
9.3.3.5. Practice#
### Exercise: One-Sided p-Value for a Supplier Claim
# A supplier claims that at most 2% of its parts are defective. A buyer inspects
# 500 parts and finds 16 defective (3.2%). Only too many defects count against
# the claim, so the test is one-sided: the statistic is the number of defective parts.
# 1. Simulate 10,000 inspections of 500 parts under the 2% model with
# ex_rng.binomial(500, 0.02, size=10000).
# 2. Compute the p-value: the share of simulated counts that are 16 or more.
# 3. Decide at the 5% cutoff.
# Print exactly:
# p-value: 0.0477
# Decision: reject the null
import numpy as np
ex_rng = np.random.default_rng(5)
ex_defective = 16
### Your code starts here.
### Your code ends here.
p-value: 0.0477
Decision: reject the null
9.3.4. Decision Errors#
A test makes its decision from random data, so the decision can be wrong in two different ways:
Decision |
The null hypothesis is true |
The null hypothesis is false |
|---|---|---|
Reject the null |
Type I error (a false alarm) |
Correct decision |
Do not reject the null |
Correct decision |
Type II error (a missed effect) |
A Type I error rejects a null hypothesis that is actually true. The cutoff controls how often this happens: if you reject whenever the p-value is below 5%, then a correctly calibrated test has a long-run false-alarm rate of about 5% or less when the null is true. Discrete test statistics can make the rate lower. That is why the cutoff alpha is called the significance level of the test.
A Type II error fails to reject a null hypothesis that is actually false. How often this happens depends on how far the truth is from the null hypothesis and on the sample size. Small samples often miss real differences.
For the traffic split, a Type I error means stopping a healthy test and hunting for a bug that is not there, which wastes analyst time. A Type II error means letting a broken tool run, so that every later comparison between versions rests on unequal groups. For an online store, the second error may cost more. Lowering the cutoff from 5% to 1% makes Type I errors rarer but Type II errors more common, unless the store collects more data.
The simulation can show both errors. First, make the null hypothesis true: run 1,000 weeks of a fair tool and apply the 5% rule to each, using the null distribution from Step 3.
def p_value_for(distances):
# For each distance, the share of simulated distances at least as large
return np.array([np.mean(simulated_distances >= d) for d in distances])
fair_counts = rng.binomial(n_visitors, 0.5, size=1000)
fair_p_values = p_value_for(split_distance(fair_counts))
print('Fair weeks that raise a false alarm at 5%:', np.sum(fair_p_values < 0.05), 'of 1000')
Fair weeks that raise a false alarm at 5%: 39 of 1000
A little under 5% of the fair weeks are flagged (39 of 1,000 here), close to the Type I error rate the cutoff promises. It is slightly below 5% because the counts of visitors are whole numbers, so the p-values take discrete steps. Now make the null hypothesis false: the tool secretly sends 51% of visitors to version B. How often does the same rule catch it?
biased_counts = rng.binomial(n_visitors, 0.51, size=1000)
biased_p_values = p_value_for(split_distance(biased_counts))
print('Biased weeks the 5% rule catches:', np.sum(biased_p_values < 0.05), 'of 1000')
print('Biased weeks missed (Type II errors):', np.sum(biased_p_values >= 0.05), 'of 1000')
Biased weeks the 5% rule catches: 412 of 1000
Biased weeks missed (Type II errors): 588 of 1000
Even with 8,000 visitors, the test catches this 51% bias in only about 4 weeks out of 10 (412 of 1,000 here) and misses it in the rest. A real but modest problem can easily go unnoticed. With fewer visitors the test would miss it even more often, and only a larger sample makes it dependable.
Many tests and false alarms. A 5% false-alarm rate is small for one test, but analysts often run many tests. Suppose a company runs 20 independent tests in which the null hypothesis is true every time, such as checking 20 different tools that are all fair. Each test has a 5% chance of a false alarm, so on average 20 x 0.05 = 1 test will be flagged. The chance of at least one false alarm is 1 - 0.95^20, about 64%. The simulation below runs 20 fair tools, then repeats that 1,000 times. The argument size=(1000, 20) asks rng.binomial for a 2-D array of counts with 1,000 rows and 20 columns: each row is one run, and each column is one tool. np.sum(..., axis=1) adds across each row, so alarms_per_run holds the number of false alarms in each of the 1,000 runs. The simulated averages are a little lower than 1 and 64% for the same discreteness reason as above (about 0.9 flagged per run and about 61% of runs with at least one).
one_run = p_value_for(split_distance(rng.binomial(n_visitors, 0.5, size=20)))
print('False alarms among 20 fair tools, one run:', np.sum(one_run < 0.05))
many_runs = p_value_for(split_distance(rng.binomial(n_visitors, 0.5, size=20000))).reshape(1000, 20)
alarms_per_run = np.sum(many_runs < 0.05, axis=1)
print('Average false alarms per run of 20 tests:', np.mean(alarms_per_run))
print('Share of runs with at least one false alarm:', np.mean(alarms_per_run >= 1))
print('Calculation, 1 - 0.95 ** 20:', round(1 - 0.95 ** 20, 3))
False alarms among 20 fair tools, one run: 1
Average false alarms per run of 20 tests: 0.884
Share of runs with at least one false alarm: 0.609
Calculation, 1 - 0.95 ** 20: 0.642
A manager who reads only the flagged tests from a long list will see “significant” results even when nothing is going on. When you run many tests, report how many you ran, expect about one false alarm per 20 tests at the 5% level, and treat a single flagged result among many as a lead to check, not as a finding.
9.3.4.1. Practice#
### Exercise: False Alarms at a 1% Cutoff
# A company monitors 50 fair tools at once. Each tool has a 5% (or 1%) chance of
# a false alarm in a week when it is fair.
# 1. Compute the expected number of false alarms per week at a 5% cutoff
# (number of tools times the cutoff).
# 2. Simulate 10,000 weeks with ex_rng.binomial(50, 0.01, size=10000): each value is
# the number of false alarms in one week at a 1% cutoff.
# 3. Print the expected count at 5%, the average simulated count at 1% (2 decimals),
# and the share of weeks with at least one false alarm at 1% (3 decimals).
# Print exactly:
# Expected false alarms at 5%: 2.5
# Average false alarms at 1%: 0.49
# Weeks with at least one false alarm at 1%: 0.391
import numpy as np
ex_rng = np.random.default_rng(11)
ex_tools = 50
### Your code starts here.
### Your code ends here.
Expected false alarms at 5%: 2.5
Average false alarms at 1%: 0.49
Weeks with at least one false alarm at 1%: 0.391
9.3.5. Statistical and Practical Significance#
Statistical significance is not practical significance, the real-world size and business value of an effect. A p-value answers one question: would data like these be surprising if the null hypothesis were true? It does not say how large the effect is. With enough data, even a trivial effect becomes statistically significant.
Suppose a checkout test pooled across a partner network of about 80 million sessions estimates a purchase-rate increase from 10.00% to 10.02%, with p = 0.003. Only a test that large could detect such a small difference. At a preselected 5% level, the result is statistically significant. For this store’s 100,000 monthly visits, the estimated increase is 20 purchases. At $10 contribution per purchase, that is $200 per month. A $1,000 monthly operating cost would exceed the estimated gain. The statistical conclusion alone does not justify rollout. The effect estimate is uncertain too, so report that uncertainty when it is available.
store_visits = 100000
rate_before = 0.1000
rate_after = 0.1002
contribution = 10
monthly_operating_cost = 1000
extra_purchases = store_visits * (rate_after - rate_before)
net_gain = extra_purchases * contribution - monthly_operating_cost
print('Estimated extra purchases per month:', round(extra_purchases))
print('Estimated gain before costs ($):', round(extra_purchases * contribution))
print('Estimated net monthly gain ($):', round(net_gain))
Estimated extra purchases per month: 20
Estimated gain before costs ($): 200
Estimated net monthly gain ($): -800
The result is statistically significant yet loses money. The reverse also happens: a small test can show a large, valuable difference that is not significant because there is too little data. In both cases the p-value and the effect size answer different questions. Ask both: is the effect unlikely to be chance, and is it big enough to matter?
9.3.5.1. Practice#
### Exercise: Interpret a Business Result
# A larger store's checkout change shows a statistically significant
# purchase-rate gain of 0.03 percentage points in a large pooled test.
# Assume 1,000,000 visits per month, $10 contribution per extra purchase,
# and $2,500 monthly operating cost.
# Compute the estimated extra purchases and net monthly contribution.
# Then print whether the change is worth rolling out (yes if the net monthly
# contribution is positive, otherwise no).
# Print exactly:
# Estimated extra purchases: 300
# Estimated net monthly contribution: 500
# Worth rolling out: yes
visits = 1000000
increase_percentage_points = 0.03
contribution_per_purchase = 10
monthly_cost = 2500
### Your code starts here.
### Your code ends here.
Estimated extra purchases: 300
Estimated net monthly contribution: 500
Worth rolling out: yes
9.3.6. Section Practice#
Practice the four steps on a new case: state the hypotheses, compute the statistic, simulate, and decide. Chapter 10 extends the same method to comparing two groups, beginning with A/B Testing.
### Exercise: Test a New Case: Hypotheses and p-Values
# A website claims that 25% of visitors click its banner. In a sample of 400 visitors,
# 120 clicked (30%). The test statistic is | sample percent - 25 |.
# 1. Compute the observed statistic.
# 2. Simulate 10,000 samples of 400 visitors under the 25% model and compute the
# statistic for each: ex_rng.binomial(400, 0.25, size=10000) gives the click counts.
# 3. Compute the p-value and decide at the 5% cutoff.
# Print exactly:
# Observed statistic: 5.0
# P-value: 0.0243
# Decision: reject the null
import numpy as np
ex_rng = np.random.default_rng(7)
clicks = 120
visitors = 400
### Your code starts here.
### Your code ends here.
Observed statistic: 5.0
P-value: 0.0243
Decision: reject the null