…
…
Statistics and Data Analysis Fundamentals · Lesson 28 / 44 · Inference by simulation
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The marketing brochure says "75% of our customers are satisfied (rating 4–5)", but of the 300 customers in the survey, 214 gave a 4 or a 5 (71.3%), and the team split in two: "the brochure is lying" and "the difference is chance". The same day, management wants to present the return result from the previous lesson (share 0.0025) as "the probability that our return rate is above 5% is 99.75%". Which of the two sentences is right, and which is wrong?
In lesson 27 you built the whole mechanism for testing a claim: you turned the claim into a chance model (H₀), simulated thousands of times how the data would look if that model were true, and checked where the observed result fell in this null distribution. In the end you had one number left: "the share of results as extreme as the observed one". In this lesson you do not learn a new method. You give that number its name, you turn it into a decision, and you filter out the most common ways to misread it.
By the end of the lesson you will be able to write two report sentences yourself:
| Question | p-value | Decision (α = 0.05) | Report sentence |
|---|---|---|---|
| Is the return rate above 5%? | 0.0025 (one-sided) | H₀ is rejected | "If the true rate were 5%, 64 or more returns in 885 orders would happen about once in 400 six-month periods; the data do not fit the 5% claim." |
| Is the 75% in the brochure correct? | 0.159 (two-sided) | H₀ is not rejected | "If the true rate were 75%, a result this far away would happen in about 1 survey out of 6; there is not enough evidence to reject the 75% claim." |
In this lesson you will:
Remember the return question from lesson 27. Management said "a reasonable return rate is 5%"; at Bazaar there were 64 returns in 885 orders (7.2%). The logistics manager said "this difference could be chance". We asked: if the true rate were 5%, how often would a six-month period of 885 orders show 64 or more returns? Let's repeat the same calculation with 10,000 trials:
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") n = len(orders) observed = (orders["status"] == "returned").sum() rng = np.random.default_rng(42) simulated = rng.binomial(n, 0.05, size=10_000) p_value = (simulated >= observed).mean() print(n, "orders,", observed, "returns") print("p-value:", p_value)
Output885 orders, 64 returns
p-value: 0.0016Only 16 of the 10,000 simulated six-month periods had 64 or more returns. In lesson 27 you got 0.0025 with 100,000 trials. When the number of trials changes, the third decimal moves, but the result "a few in a thousand" does not. The management report says 0.0025, so we will continue with that number in this lesson.
The name of this number is the p-value: the probability of seeing a result as extreme as the observed one, or more extreme, if H₀ were true. The definition is short, but every part does a job, so let's build it slowly. "If H₀ were true" says in which world the calculation is done: an imaginary world where the true rate is exactly 5%. "In a sample of the same size" keeps the comparison fair: we compare 885 orders with 885 orders. "As extreme as the observed one" says what we count: not only exactly 64, but 64 and above. The probability of any single value is always small (even exactly 44 returns is rare); the real question is how common results this far away or farther are. Finally, "probability of seeing" says that the result is a share between 0 and 1.
In short, the p-value measures how surprising the data are, if H₀ is true. A small p-value means "if H₀ were true, this data would be very rare". A large p-value means "even if H₀ were true, data like this would be common". Put the parts of the definition in the right order:
Put the parts of the sentence that defines the p-value in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Let's follow what "more extreme" means in a small example. Think of the list below as ten simulated results made under H₀ (in reality there would be thousands). The expected value under H₀ is 5, and the observed value is 7. The loop counts two things: results of 7 or more (one direction), and results at least as far from the expected value as 7 is, that is, at least 2 away from 5 (two directions). After you watch it, change observed to 8 or 6 and watch again:
Run the code line by line: see which line runs next, the variable boxes and the output.
null_results = [5, 3, 7, 4, 6, 8, 5, 2, 6, 5] expected = 5 observed = 7 one = 0 two = 0 for x in null_results: if x >= observed: one = one + 1 if abs(x - expected) >= abs(observed - expected): two = two + 1 print("One-sided:", one, "/", len(null_results), "=", one / len(null_results)) print("Two-sided:", two, "/", len(null_results), "=", two / len(null_results))
The one-sided count includes only 7 and 8: 2 / 10 = 0.2. The two-sided count also includes 3 and 2, because they are also at least 2 away from the expected 5, only on the other side: 4 / 10 = 0.4. Which one you count depends on the question itself; we will come back to this difference in section 5.
Now let's look at management's sentence: "p = 0.0025, so the probability that our return rate is above 5% is 99.75%." It sounds reasonable, because 1 − 0.0025 = 0.9975. But the sentence is wrong, and you know the source of the mistake from lesson 24: a direction mix-up.
The p-value is a conditional probability: P(data this extreme | H₀). H₀ stands on the right side of the bar; it answers the question "if H₀ is true, how surprising is the data?" Management's sentence asks the opposite direction: P(H₀ | data), that is, "after seeing this data, the probability that H₀ is true". In lesson 24 you saw that the sentences "the filter catches 95% of fakes" and "95% of the alarms are fake" are different; the same thing is happening here. Our simulation always ran in the world where H₀ is true. It never calculated how likely H₀ itself is, and it cannot.
There are three more things the p-value does not say. First, it is not "the probability that the result is due to chance". This sentence also quietly states the probability of H₀ ("due to chance" = "H₀ is true"). Second, it does not tell the size of the effect. p = 0.0025 does not mean "the return rate is much bigger than 5%"; it says only that the data do not fit 5%. How much bigger the rate is, is a separate question (lesson 30). Third, it does not say whether a result matters in practice. We will see this with an example at the end.
Match the six sentences as correct or wrong interpretations:
Return test: H₀ is "the true rate is 5%", and the p-value is 0.0025. Is each sentence a correct interpretation or a wrong one?
For each row, pick its match from the list, then check.
The correct sentence to suggest to management is: "If the true return rate were 5%, the probability of seeing 64 or more returns in 885 orders would be about 0.0025, which is about once in 400 six-month periods. The data do not fit the 5% claim." It is less dramatic, but it is correct.
The p-value is a continuous measure: 0.0025 is very surprising, 0.4 is not surprising at all. But in business a decision is often needed: will the return process be reviewed, will the brochure be changed? For that, a threshold is chosen before the test. This threshold is called the significance level, and it is written α ("alpha"). The rule is simple: if p < α, H₀ is rejected; if p ≥ α, H₀ is not rejected.
The most common value is α = 0.05. There is no reason from nature behind it; it is a widespread habit. Where a false alarm is expensive (for example, putting a medicine on the market), a stricter value such as 0.01 is chosen, and in exploratory work a looser one such as 0.10. What matters is that the threshold is chosen before the test, without looking at the data. Adjusting the threshold after seeing the p-value is like changing the rules after the match is over. α has one more meaning: it is the probability of wrongly rejecting H₀ when it is actually true. We will look at this type of error and its cost in detail in lesson 33.
An example from outside Bazaar: a school canteen thinks the new toastie makes up more than 30% of its sales. H₀: the share is 30%; H₁: the share is more than 30%. Their simulation with one week of receipts gave p = 0.03. Below, change both α and p and see how the decision changes. In particular, compare p = 0.049 with p = 0.051:
Canteen test: H₀ is "the toastie's sales share is 30%", H₁ is "more than 30%". Change α and p; how does the decision change?
Pick a value; predict the output first, then look.
1alpha = 0.052p = 0.033print("Canteen test: p =", p, "| alpha =", alpha)4if p < alpha:5 print("p < alpha: H0 is rejected.")6 print("There is evidence that the share is above 30%.")7else:8 print("p >= alpha: H0 is not rejected.")9 print("There is not enough evidence that the share is above 30%.")
Canteen test: p = 0.03 | alpha = 0.05 p < alpha: H0 is rejected. There is evidence that the share is above 30%.
Faded lines didn't run with this value. The same p-value gives different decisions with different α values. At α = 0.05, 0.049 and 0.051 fall on different sides, but they carry almost the same evidence. This is why α is chosen in advance and p is always reported as a number.
At α = 0.05, p = 0.049 gives "rejected" and p = 0.051 gives "not rejected". But these two p-values carry almost the same evidence: if H₀ were true, a result this extreme would happen about once in 20 weeks, in both cases. The line between them was drawn by habit, not by nature. This is why a good report does not write only "significant / not significant"; it gives the p-value as a number and lets the reader see the strength of the evidence. The sentence "p = 0.051; at α = 0.05, H₀ is not rejected; very close to the limit" is much more honest than "the result is not significant".
What do you say when p ≥ α? This is where the most common mistake happens. Let's look at desktop orders: 23 returns in 369 orders, a rate of 6.2%. This is also above 5%. H₀: the true return rate of desktop is 5%; H₁: it is above 5%.
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") desk = orders[orders["device"] == "desktop"] n = len(desk) observed = (desk["status"] == "returned").sum() rng = np.random.default_rng(42) simulated = rng.binomial(n, 0.05, size=10_000) print(n, "orders,", observed, "returns, rate", round(observed / n, 3)) print("Mean under H0:", round(simulated.mean(), 1)) print("p-value:", round((simulated >= observed).mean(), 3))
Output369 orders, 23 returns, rate 0.062
Mean under H0: 18.4
p-value: 0.163p ≈ 0.16: a store with a 5% rate would also see 23 or more returns in 369 orders about once in 6 six-month periods. It is larger than α = 0.05, so H₀ is not rejected. But what does this mean?
For desktop orders, p ≈ 0.16 (α = 0.05). Which conclusion is correct?
For this reason, decision language has two patterns, and both are built on H₀: "H₀ is rejected" and "H₀ is not rejected". We do not say "H₀ is accepted" or "H₀ is proven". The same care applies when you turn it into a sentence with context: not "the desktop return rate is 5%", but "there is not enough evidence that the desktop return rate is above 5%". Also think about why the evidence was not enough: 369 orders are far fewer than 885. With less data, chance plays a bigger role (lesson 25), so a difference of the same size looks less surprising. With more data, the same rate could easily have given "rejected".
Now let's move to the brochure. The brochure says "75% of our customers are satisfied". The question is "is the 75% in the brochure correct?" For this question, a rate below 75% and a rate above 75% both contradict the brochure; both mean "the brochure is wrong". In this case H₁ is: rate ≠ 0.75, and a two-sided p-value is calculated: results that fall at least as far from the expected value as the observed one, in either direction, are counted.
The return question was different. There, management asked only "is our return rate above the target?"; a rate below 5% would worry nobody. So H₁ was: rate > 0.05, and a one-sided p-value was calculated: only the right tail.
The calculation for the brochure: under H₀, the expected number of satisfied customers among 300 is 300 × 0.75 = 225. The observed number is 214, which is 11 below the expected. The two-sided p-value is the share of results in the null distribution that are at least 11 away from 225: 214 or fewer, or 236 or more. In code we write this as np.abs(simulated - expected) >= distance; the absolute value catches both sides at once (like the abs in the loop you followed).
import pandas as pd import numpy as np survey = pd.read_csv("survey.csv") satisfied = survey["satisfaction"] >= 4 n = len(survey) observed = satisfied.sum() claim = 0.75 expected = n * claim rng = np.random.default_rng(42) simulated = rng.binomial(n, claim, size=10_000) distance = abs(observed - expected) two_sided = (np.abs(simulated - expected) >= distance).mean() one_sided = (simulated <= observed).mean() print("Observed:", observed, "/", n, "=", round(observed / n, 3)) print("Expected:", expected, "| distance:", distance) print("Two-sided p:", round(two_sided, 3)) print("One-sided p:", round(one_sided, 3))
OutputObserved: 214 / 300 = 0.713
Expected: 225.0 | distance: 11.0
Two-sided p: 0.159
One-sided p: 0.083Two-sided p = 0.159: if the true rate were 75%, a result at least 11 away from 225 in a survey of 300 people would happen in about 1 survey out of 6. At α = 0.05, H₀ is not rejected. The one-sided p-value (only "214 or fewer") is 0.083, about half of the two-sided one, because the null distribution is almost symmetric and the two tails are about equal. This is why "one-sided × 2" is also used as a shortcut for the two-sided p-value (0.166); when the distribution is symmetric, the result is close.
Now the dangerous part. An analyst looked at the data, saw that the rate was below 75%, and said "then let the question be 'is it lower?'". They chose the one-sided p-value: 0.083. If they were using α = 0.10, this move would turn "not rejected" into "rejected". Choosing the direction after seeing the data cuts the p-value in half artificially, because choosing the side where the observed value fell quietly deletes the possibility that "the other side could also have happened". The rule: the direction is chosen from the question itself, without looking at the data. If the question is "is it different?", count two tails; if it is "is it bigger?" or "is it smaller?" and this is clear before the data are collected, count one tail.
In the cell below we plot the null distribution and the observed value; the two dashed lines are the limits of the two-sided count (225 − 11 and 225 + 11). Run it first, then change claim:
Try it now· not graded; doesn't affect progress
When you set claim = 0.70, the two-sided p rises to 0.66; when you set claim = 0.80, it drops to 0.0005. Same data, different claims: the data fit both 70% and 75%, but not 80%. This also shows why "not rejected" is not "proven": with the same survey, both 70% and 75% are not rejected, but they cannot both be the true rate.
A good test report has five parts: the context (what was asked), the observed result (what was found, in how many units), the p-value (as a number, with its direction), the decision (according to α), and the limit (what the result does not say). For the brochure:
"In the survey, 71.3% of 300 customers gave a 4–5 rating. If the true rate were 75%, a result this far away would happen about 1 time in every 6 surveys (two-sided p = 0.16); at α = 0.05 there is not enough evidence to reject the 75% claim. This does not mean the rate is exactly 75%; in lesson 30 we will see how much it could be, with an interval."
This pattern has no words such as "lie", "proven", or "certain". The p-value is also translated into everyday language as "1 time in every 6 surveys", so even a manager who does not know statistics can sense the strength of the evidence.
One last warning: a small p-value does not mean a big or important effect. With a very large dataset (for example, one million orders), if the return rate is 5.1%, the p-value against the 5% claim can be very small; but a difference of 0.1 percentage points may be unimportant for the business. The p-value answers "is there a difference?", and the effect size answers "how big is the difference?". We will separate these two in detail in lesson 33. Now take the place of the marketing manager:
The marketing manager will present the survey result (71.3% of 300 customers are satisfied, claim 75%, two-sided p = 0.16) in the management meeting in one sentence. Which sentence should they choose?
Pick an option and see what happens. There are no points; you can try the other options too.
Let's see with an example from outside Bazaar that the decision depends on α, not only on the context. In a board game, a player complains that the die gives a 6 too often: 30 sixes in 120 rolls. With a fair die the expected number is 120 / 6 = 20. The question is "is the die fair?", so the direction is not clear in advance: a 6 appearing too rarely would also show that the die is faulty. Let's test it two-sided:
import numpy as np rng = np.random.default_rng(42) simulated = rng.binomial(120, 1/6, size=10_000) print("Expected:", 120 / 6) p_two = (np.abs(simulated - 20) >= 10).mean() print("Two-sided p:", round(p_two, 4)) for alpha in [0.05, 0.01]: print("alpha =", alpha, "->", "H0 rejected" if p_two < alpha else "H0 not rejected")
OutputExpected: 20.0
Two-sided p: 0.0208
alpha = 0.05 -> H0 rejected
alpha = 0.01 -> H0 not rejectedThe if ... else in the last line is a one-line condition: if the condition is true, the text on the left is chosen; if not, the text on the right. A fair die gives a count of sixes at least 10 away from 20 in 120 rolls in about 1 session out of 50. Someone who chooses α = 0.05 decides "the die is not fair"; someone who chooses α = 0.01 does not. Same data, same p-value, different decision. This is why it is important to write α in advance and always report p as a number.
What should someone who chose α = 0.01 for the die test (p = 0.021) say?
Now you can test a rate against a single claim and report the result with the right sentence. But the real questions in business often compare two groups: did the new checkout page bring more sales than the old one? In the next lesson we will apply the same simulation logic to two groups.
Let's test the brochure claim separately for mobile and desktop customers. One generator is used for the two groups in turn.
import pandas as pd import numpy as np survey = pd.read_csv("survey.csv") rng = np.random.default_rng(42) for device, group in survey.groupby("device"): satisfied = group["satisfaction"] >= 4 n, k = len(group), satisfied.sum() simulated = rng.binomial(n, 0.75, size=10_000) p = (np.abs(simulated - n * 0.75) >= abs(k - n * 0.75)).mean() print(device, "|", k, "/", n, "=", round(k / n, 3), "| two-sided p:", round(p, 3))
Outputdesktop | 88 / 126 = 0.698 | two-sided p: 0.21
mobile | 126 / 174 = 0.724 | two-sided p: 0.49In both groups H₀ is not rejected. Desktop has the lower rate, yet its p-value is large, because the group is small (126 people): with less data, chance plays a bigger role.
When we test the same survey against different claims, we can see which rates fit the data. The generator is set up again for each claim, so the 75% row is the same as in the lesson.
import pandas pd
numpy np
survey = pd.read_csv()
observed = (survey[] >= 4).()
claim [0.65, 0.70, 0.75, 0.80]:
rng = np.random.default_rng(42)
expected = 300 * claim
simulated = rng.binomial(300, claim, size=10_000)
p = (np.(simulated - expected) >= (observed - expected)).mean()
decision = p < 0.05
(, claim, , (p, 4), , decision)Saying "p = 0.16, so the 75% in the brochure is correct". A non-significant result does not show that H₀ is proven; it shows that there is not enough evidence to reject it. The same survey also does not reject the 70% claim (p = 0.66), but the two rates cannot both be true. The correct statement: "There is not enough evidence that the true rate is different from 75% (two-sided p = 0.16); the rate observed in the survey is 71.3%."
np.abs(simulated - expected) >= distance); the direction is chosen from the question, without looking at the data.Next lesson: You tested a single rate against a claim; now you will test an A/B experiment that compares two groups (the old and the new checkout page) by shuffling the labels in a simulation.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputClaim 0.65 | p = 0.0246 | H0 rejected
Claim 0.7 | p = 0.6607 | H0 not rejected
Claim 0.75 | p = 0.1589 | H0 not rejected
Claim 0.8 | p = 0.0005 | H0 rejected70% and 75% are not rejected; 65% and 80% are rejected. The claims that are not rejected form an interval; the confidence interval in lesson 30 is built on exactly this idea.