Module contents
Lesson 10 of 27Core 100 min

Hypothesis testing and p-values

Understand hypothesis tests and p-values, interpret type I and II errors and test–interval duality, quantify false positive risk and use equivalence testing.

After this lesson you can

  • Define test size, power, type I and type II errors and valid p-values.
  • Explain test–confidence interval duality and distinguish one-sided and two-sided tests.
  • Interpret p-values correctly and quantify false positive risk using prior prevalence and power.
  • Apply two one-sided tests to assess equivalence with a prespecified margin.

Before you start

Motivation: did the new detector really improve?

Your team trained a new vulnerability-detector version and compares it with the current one on 40 repositories with known vulnerabilities. For each repository you measure the new-minus-old F1 difference in percentage points. (The data in this lesson are simulated: there is no real benchmark behind them.) The result is:

[ ]An ambiguous resultBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
d = rng.normal(1.0, 4.0, 40)        # diferencia de F1 (nueva menos antigua) en 40 repositorios; simulado, media real 1.0
r = stats.ttest_1samp(d, 0.0)
ic = r.confidence_interval(0.95)
print(f"media {d.mean():.3f}   desviación {d.std(ddof=1):.3f}   n = {d.size}")
print(f"t = {r.statistic:.3f}   p bilateral = {r.pvalue:.4f}")
print(f"IC 95 %: [{ic.low:.3f}, {ic.high:.3f}]")

The new version gains 1.01 points on average, but with deviation 3.77 across repositories that could be noise. The pp value is 0.0975. What do you conclude? Three tempting interpretations are all superficially defensible.

  1. “p=0.0975>0.05p = 0.0975 > 0.05, so there is no improvement.” The 95 % interval is [−0.19,2.22][-0.19, 2.22]: it includes improvements of more than 2 points. Data that do not rule out zero are not evidence that the effect is zero.
  2. “p≈0.10p \approx 0.10, so there is a 90 % chance it improves.” A pp value is a probability about data assuming a hypothesis, not a probability of the hypothesis. This is the most widespread confusion in applied statistics.
  3. “With a one-sided test, p=0.0488<0.05p = 0.0488 < 0.05: now it improves.” Same data, same model, opposite conclusion. This is legitimate only if “one-sided” was chosen before seeing the effect’s direction; choosing afterward is a trap doubling the false-positive rate.

This lesson builds a framework for answering without getting lost. It covers five questions:

  • What is a test? Hypotheses, statistic, rejection region and level, and the two possible errors and which is controlled.
  • What is (and is not) a pp value? Its exact definition, uniform distribution under the null, and misinterpretations catalogued in the ASA statement.
  • How tests and intervals relate: a confidence interval is an inverted test, and a test is an interval read backward.
  • What fraction of “significant” findings are false, and why that depends on things the pp value cannot see.
  • How to demonstrate absence of a relevant effect: equivalence tests, which reverse the burden of proof.

We use a statistic’s sampling distribution, pivotal quantities, and confidence intervals from the previous lesson, and normal theory from lesson 2.

Anatomy of a hypothesis test

Start with a statistical model {Pθ:θ∈Θ}\{P_\theta : \theta \in \Theta\} for data XX. A hypothesis is a claim about the parameter, that is, a subset of Θ\Theta. A test compares two mutually exclusive, exhaustive hypotheses: null H0:θ∈Θ0H_0 : \theta \in \Theta_0 and alternative H1:θ∈Θ1=Θ∖Θ0H_1 : \theta \in \Theta_1 = \Theta \setminus \Theta_0. A hypothesis is simple if it fixes one value (Θ0={θ0}\Theta_0 = \{\theta_0\}), otherwise composite.

The definition separates two worlds. For θ∈Θ0\theta \in \Theta_0, γ(θ)\gamma(\theta) is the probability of incorrectly rejecting: we want it small. For θ∈Θ1\theta \in \Theta_1, γ(θ)\gamma(\theta) is the probability of correctly rejecting: we want it large. A good test has power below α\alpha in Θ0\Theta_0 and rising toward 1 in Θ1\Theta_1.

The canonical example: the zz test

Let X1,…,Xn∼iidN(μ,σ2)X_1, \dots, X_n \iid \Normal(\mu, \sigma^2) with known σ\sigma, and test H0:μ≤μ0H_0 : \mu \le \mu_0 against H1:μ>μ0H_1 : \mu > \mu_0. The natural statistic is the standardized mean,

T=n (Xˉ−μ0)σ,T = \frac{\sqrt n\,(\bar X - \mu_0)}{\sigma},

and we reject for large values: R={T≥c}\mathcal{R} = \{T \ge c\}. If the true mean is μ\mu, then T∼N(δ,1)T \sim \Normal(\delta, 1) with δ=n (μ−μ0)/σ\delta = \sqrt n\,(\mu - \mu_0)/\sigma, so

γ(μ)=Pμ(T≥c)=1−Φ(c−δ).\gamma(\mu) = \Pr_\mu(T \ge c) = 1 - \Phi\big(c - \delta\big).

γ\gamma increases in μ\mu, so its supremum over Θ0={μ≤μ0}\Theta_0 = \{\mu \le \mu_0\} occurs at boundary μ=μ0\mu = \mu_0 (where δ=0\delta = 0): size is 1−Φ(c)1 - \Phi(c). For exactly α\alpha, take c=z1−αc = z_{1-\alpha}, the standard normal’s 1−α1 - \alpha quantile. With α=0.05\alpha = 0.05, c=1.645c = 1.645.

When σ\sigma is unknown replace it with sample standard deviation SS; the statistic becomes T=n(Xˉ−μ0)/ST = \sqrt n(\bar X - \mu_0)/S, which under μ=μ0\mu = \mu_0 follows Student’s tt with n−1n - 1 degrees of freedom (normal theory). It is a pivot under the null: its distribution has no unknown parameters, allowing calibration of the threshold. The general recipe has four ingredients:

IngredientIn the zz testRequirement
HypothesesH0:μ≤μ0H_0 : \mu \le \mu_0 versus H1:μ>μ0H_1 : \mu > \mu_0Fixed before seeing data
StatisticT=n(Xˉ−μ0)/σT = \sqrt n(\bar X - \mu_0)/\sigmaLarge when H1H_1 is plausible
Null distributionT∼N(0,1)T \sim \Normal(0, 1) if μ=μ0\mu = \mu_0Calculable without unknown parameters
Rejection regionT≥z1−αT \ge z_{1-\alpha}Size ≤α\le \alpha

The asymmetry between hypotheses is deliberate and central. H0H_0 is presumed until data make it untenable (the new detector is no better, the drug does not work, the estimator is unbiased), and the test makes erroneous rejection rare. The burden of proof lies with H1H_1. Thus not rejecting H0H_0 is not accepting it: the data did not suffice to refute it, possibly because H0H_0 is true or because the test lacked power.

Two errors and the cost of the threshold

A test can err in two ways.

H0H_0 trueH1H_1 true
Reject H0H_0Type I error (false positive), probability ≤α\le \alphaCorrect, probability 1−β1 - \beta (power)
Do not reject H0H_0CorrectType II error (false negative), probability β\beta

Type I and type II errors have immediate expressions in terms of power: type I is γ(θ)\gamma(\theta) for θ∈Θ0\theta \in \Theta_0, bounded by level α\alpha; type II is β(θ)=1−γ(θ)\beta(\theta) = 1 - \gamma(\theta) for θ∈Θ1\theta \in \Theta_1, which depends on the true alternative. While α\alpha is a design decision, β\beta is not chosen: it follows from α\alpha, nn, noise and actual effect size.

For the one-sided zz test the calculation is explicit. With standardized effect d=(μ−μ0)/σd = (\mu - \mu_0)/\sigma and δ=dn\delta = d\sqrt n,

β=Φ(z1−α−δ),1−β=1−Φ(z1−α−dn).\beta = \Phi\big(z_{1-\alpha} - \delta\big), \qquad 1 - \beta = 1 - \Phi\big(z_{1-\alpha} - d\sqrt n\big).

Four facts follow directly. Power rises with effect dd and n\sqrt n, depending on them only through their product δ\delta: doubling effect equals quadrupling data. It falls when a smaller α\alpha is required, because z1−αz_{1-\alpha} grows. And as d→0d \to 0, power tends to α\alpha: a tiny effect is indistinguishable from the null, the only thing that ought to be indistinguishable.

Interactiveα, β and the threshold
Distribution of statistic ZZ under H0H_0 (gray) and under the alternative (blue)
H₀H₁reject if Z ≥ c
Power versus α\alpha (log scale): each test's options
0.05
  • α (type I)
  • β (type II)
  • power
  • with current data
  • with 4n observations
Alternative
0.50
25
1.65
α\alpha: type I error5.00 %
β\beta: type II error19.6 %
Power 1−β1 - \beta80.4 %
δ=dn\delta = d\sqrt{n} (shift)2.50
β\beta if α=0.05\alpha = 0.05 | α=0.001\alpha = 0.00119.6 % | 72.2 %
nn for power 0.8 at this α\alpha25
The two densities are the statistic ZZ under H0H_0 (grey) and the alternative (blue). Drag the threshold (or click where you want it): red area is α\alpha, orange is β\beta. With fixed nn and dd, lower α\alpha and see that β\beta always rises. The right panel plots this test's menu: power bought at each level α\alpha; the dashed curve is the same test with 4n4n observations, the only way to improve both at once. Try the two-sided alternative and find the sample size for power 0.8.

Three lessons from the interactive. Moving the threshold is not free. With d=0.5d = 0.5 and n=25n = 25 (δ=2.5\delta = 2.5), a one-sided test at α=0.05\alpha = 0.05 has β=0.196\beta = 0.196, at α=0.01\alpha = 0.01 it rises to β=0.431\beta = 0.431, and at α=0.001\alpha = 0.001 to β=0.722\beta = 0.722. Rarer false positives cost more missed real effects. Only data move the curve. With 4n=1004n = 100 observations δ\delta doubles and the same α=0.001\alpha = 0.001 yields 97 % power. Effect size matters. Sample size for power 0.8 at α=0.05\alpha = 0.05 is n=((z1−α+z0.8)/d)2=((1.645+0.842)/0.5)2≈24.7n = \big((z_{1-\alpha} + z_{0.8})/d\big)^2 = \big((1.645 + 0.842)/0.5\big)^2 \approx 24.7, i.e. 25 observations; detecting d=0.1d = 0.1 needs 619. Choosing nn before collecting data is covered in power and sample size.

The pp value

Fixing α\alpha in advance gives a binary answer. But the same T=2.5T = 2.5 would reject at 5 % and 1 %, whereas T=1.8T = 1.8 would reject only at 5 %. The pp value summarizes this: the smallest level at which rejection would occur.

For the one-sided zz test, p=1−Φ(Tobs)p = 1 - \Phi(T_{\text{obs}}); for two-sided, p=2(1−Φ(∣Tobs∣))p = 2\big(1 - \Phi(\abs{T_{\text{obs}}})\big). In the motivating example tt is 1.6981.698 with 39 degrees of freedom: the upper tail gives 0.04880.0488 and both tails 0.09750.0975.

A reading trap deserves attention. p(X)p(X) is a random variable: it changes from sample to sample. Its fundamental property is its distribution when H0H_0 is true.

Proof

(b) If FF is continuous, Pθ0(T≥t)=1−F(t)\Pr_{\theta_0}(T \ge t) = 1 - F(t) and hence p=1−F(T)p = 1 - F(T). By the probability integral transform, F(T)∼Unif⁡(0,1)F(T) \sim \Unif(0, 1) when FF is continuous. Thus P(p≤u)=P(F(T)≥1−u)=u\Pr(p \le u) = \Pr\big(F(T) \ge 1 - u\big) = u.

(a) Fix θ∈Θ0\theta \in \Theta_0 and write G(t)=Pθ(T≥t)G(t) = \Pr_\theta(T \ge t), a decreasing function. By definition p(x)≥G(T(x))p(x) \ge G(T(x)), so {p≤u}⊆{G(T)≤u}\{p \le u\} \subseteq \{G(T) \le u\}. We show P(G(T)≤u)≤u\Pr(G(T) \le u) \le u. The set A={t:G(t)≤u}A = \{t : G(t) \le u\} is an upper ray with endpoint t∗=inf⁡At^* = \inf A. If it contains t∗t^*, P(T∈A)=P(T≥t∗)=G(t∗)≤u\Pr(T \in A) = \Pr(T \ge t^*) = G(t^*) \le u. Otherwise P(T∈A)=P(T>t∗)=lim⁡t↓t∗G(t)≤u\Pr(T \in A) = \Pr(T > t^*) = \lim_{t \downarrow t^*} G(t) \le u, because G(t)≤uG(t) \le u for all t>t∗t > t^*. Finally, rejecting when p≤αp \le \alpha has probability at most α\alpha under each θ∈Θ0\theta \in \Theta_0.

∎

This theorem makes pp values useful: under the null, it is uniform, so P(p≤0.05)=0.05\Pr(p \le 0.05) = 0.05, P(p≤0.01)=0.01\Pr(p \le 0.01) = 0.01 and so on. This places any pp on a common scale regardless of statistic, model or sample size. The figure shows this by repeating the experiment thousands of times.

InteractiveUnder H₀ the p-value is uniform
Histogram of pp values (bins of 0.05; rejection region p≤0.05p \le 0.05 in red)
uniform: 1
Distribution function of pp versus the diagonal
0.05
  • replicates
  • rejections at p ≤ 0.05
  • exact distribution
  • uniform / diagonal
Statistic
20
0.00
4000 replicates
Replicates4000
Type I error rate: P(p ≤ 0.05): simulated | exact5.1 % ± 0.7 | 5.00 %
P(p≤0.01)P(p \le 0.01): simulated | exact0.9 % | 1.00 %
When H0H_0 is true and the statistic is continuous, each bin of width 0.05 receives 5% of the p values: the histogram is flat and the empirical distribution follows the diagonal. Therefore rejecting at p≤0.05p \le 0.05 is wrong 5% of the time.
Each replicate repeats the whole experiment (sample, statistic, pp value) and adds its pp to the left histogram (with effect d=(μ−μ0)/σd = (\mu - \mu_0)/\sigma in the zz case); at right is the empirical distribution function of pp against the diagonal. With true H0H_0 (d=0d = 0) the histogram is flat and the curve follows the diagonal. Increase dd: a peak near 0 appears, whose area is power. Then switch to exact binomial with n=10n = 10 and θ=0.5\theta = 0.5: pp takes only 11 values, the histogram is stepped and the curve lies below the diagonal.

With zz and d=0d = 0, rejection is 5 % at any nn. With binomial H0:θ=0.5H_0 : \theta = 0.5 versus θ>0.5\theta > 0.5 and n=10n = 10, possible pp values near 0.05 are P(X≥8)=0.0547\Pr(X \ge 8) = 0.0547 and P(X≥9)=0.0107\Pr(X \ge 9) = 0.0107: rejecting at p≤0.05p \le 0.05 is equivalent to rejecting at X≥9X \ge 9, and actual level is 1.07 %, not 5 %. This is part (a): P(p≤u)≤u\Pr(p \le u) \le u may be strict, and with discrete statistics almost always is. The test is conservative: it never exceeds α\alpha, at the cost of power. Increasing nn refines the grid of possible pp values and reduces the issue, though it never disappears entirely.

Fisher versus Neyman and Pearson

The pp value and level α\alpha come from two traditions that competed for decades and are mixed without warning in modern practice.

Fisher (years 20 to 50 of the twentieth century)Neyman and Pearson (1933)
QuestionHow compatible are these data with H0H_0?What decision controls errors in the long run?
ToolExact pp value as a graded measure of discrepancyRejection region of prespecified size α\alpha
AlternativeNot requiredEssential: defines what makes a good region (power)
GuaranteeNone over repetitions; evidence from one experimentError frequencies α\alpha and β\beta over procedure repetitions
Result“p=0.03p = 0.03”“Reject H0H_0 at level 0.05”

Fisher presented p=0.05p = 0.05 as a convenient threshold for deviations deserving attention, and in his later work (Statistical Methods and Scientific Inference, 1956) insisted no fixed level suits every case and evidence strength must be evaluated for each experiment. Neyman and Pearson built decision theory: compare tests of equal size, choose the most powerful (Neyman–Pearson lemma), and interpret α\alpha as the procedure’s error frequency, not that of a particular result. Modern practice is a hybrid: calculate pp like Fisher, compare with 0.05 like Neyman and Pearson, and say “significant” without specifying alternative or power.

The distinction matters for what can be claimed. Fixed α\alpha is a property of the procedure: “if I apply this rule to many experiments where H0H_0 is true, 5 % will be errors.” It is not a probability about this experiment. A pp value measures discrepancy, not probability of correctness. When someone says “there is a 3 % chance the result is due to chance,” suspect an unwarranted jump between these statements.

One-sided versus two-sided

The alternative determines what counts as “extreme”. With H1:μ>μ0H_1 : \mu > \mu_0 only the right statistic tail counts; with H1:μ≠μ0H_1 : \mu \neq \mu_0 both do, and for a symmetric statistic p=2min⁡{pizq,pder}p = 2\min\{p_{\text{izq}}, p_{\text{der}}\}. At the same level, the two-sided threshold is stricter (z1−α/2=1.96z_{1-\alpha/2} = 1.96 versus z1−α=1.645z_{1-\alpha} = 1.645 with α=0.05\alpha = 0.05), so the two-sided test has less power in the direction of interest and more in the opposite direction. Here “izq” and “der” denote left and right tails.

The rule is easy to state and hard to follow: choose the alternative from the problem before seeing data. A one-sided test is legitimate if an effect in the other direction would lead to exactly the same decision as no effect (e.g. “deploy the new version only if it improves; if it worsens or stays equal, keep the old one”). If effects in either direction have their own consequences, use a two-sided test.

To see why choosing afterward is a trap, suppose you inspect the sign of Xˉ−μ0\bar X - \mu_0 and then test one-sided in that direction at level α\alpha. Under H0H_0 reject when T≥z1−αT \ge z_{1-\alpha} (positive sign) or T≤−z1−αT \le -z_{1-\alpha} (negative), i.e. ∣T∣≥z1−α\abs{T} \ge z_{1-\alpha}. The probability is

Pμ0(∣T∣≥z1−α)=2α.\Pr_{\mu_0}\big(\abs{T} \ge z_{1-\alpha}\big) = 2\alpha.

With α=0.05\alpha = 0.05, rejection happens 10 % of the time under true H0H_0, presented as 5 %. In the detector example, p=0.0488p = 0.0488 is valid only if “improvement” was chosen beforehand; otherwise the honest pp is 0.09750.0975.

Duality between tests and intervals

Confidence intervals and tests are the same theory presented differently. If a 95 % interval for θ\theta excludes θ0\theta_0, reject H0:θ=θ0H_0 : \theta = \theta_0 at 5 %; if it contains it, do not reject. Conversely, values not rejected by a 5 % test form a 95 % interval.

Proof

(a) Let θ\theta be true. Then θ∉C(X)\theta \notin C(X) occurs exactly when φθ\varphi_\theta rejects true H0:θ=θH_0 : \theta = \theta, with probability at most α\alpha. Hence Pθ(θ∈C(X))≥1−α\Pr_\theta(\theta \in C(X)) \ge 1 - \alpha. (b) Read the same argument backward: Pθ0(rechazar)=Pθ0(θ0∉C(X))≤α\Pr_{\theta_0}(\text{rechazar}) = \Pr_{\theta_0}(\theta_0 \notin C(X)) \le \alpha.

∎

This is test–confidence interval duality. In pp-value terms: if pθ0(x)p_{\theta_0}(x) is the pp value of the test of H0:θ=θ0H_0 : \theta = \theta_0, then

C1−α(x)={θ0:pθ0(x)>α}.C_{1-\alpha}(x) = \{\theta_0 : p_{\theta_0}(x) > \alpha\}.

The function θ0↦pθ0(x)\theta_0 \mapsto p_{\theta_0}(x) contains every interval at once, one per level: cut it with a horizontal line at α\alpha. Two familiar examples follow immediately. Inverting the zz test gives Xˉ±z1−α/2 σ/n\bar X \pm z_{1-\alpha/2}\,\sigma/\sqrt n; inverting the tt test (the previous lesson’s pivot) gives Xˉ±tn−1, 1−α/2 S/n\bar X \pm t_{n-1,\,1-\alpha/2}\,S/\sqrt n.

Inversion has an often-overlooked practical consequence: the interval depends on the test inverted. With xx successes in nn Bernoulli trials there are three common two-sided tests of H0:θ=θ0H_0 : \theta = \theta_0, each producing one of the previous lesson’s proportion intervals:

  • Wald standardizes using estimated standard error at θ^=x/n\hat\theta = x/n, independent of θ0\theta_0: inversion gives symmetric interval θ^±zθ^(1−θ^)/n\hat\theta \pm z\sqrt{\hat\theta(1 - \hat\theta)/n}.
  • Score standardizes using null standard error θ0(1−θ0)/n\sqrt{\theta_0(1 - \theta_0)/n}: inversion gives the Wilson interval.
  • The exact test calculates binomial tails under θ0\theta_0 (doubling the smaller): inversion gives Clopper–Pearson.
InteractiveInverting tests to obtain an interval
P value of the test of H0:θ=θ0H_0: \theta = \theta_0 versus θ0\theta_0, with x=12x = 12 successes out of n=40n = 40
α = 0.05green: not rejected · red: rejected
  • p value of test of θ0\theta_0
  • region with p>αp > \alpha (interval)
  • α\alpha threshold
  • direct formula endpoints
Test to invert
40
12 (p̂ = 0.300)
0.05
601 of 601 θ₀ values
Interval by inversion (Score, 95 %)[0.181, 0.454]
Direct interval (Wilson)[0.181, 0.454]
Maximum endpoint difference0.0000
H0:θ=0.500H_0: \theta = 0.500p = 0.011 → rejected
The score test uses the standard error at θ0\theta_0, θ0(1−θ0)/n\sqrt{\theta_0(1 - \theta_0)/n}. Inverting it gives the Wilson interval: asymmetric, within [0,1][0, 1], and with good coverage even for small nn.
For each candidate θ0\theta_0 on a 601-point grid, perform the two-sided test of H0:θ=θ0H_0 : \theta = \theta_0 on observed data and color green if not rejected. The green region (where pp exceeds α\alpha) is the confidence interval; dotted lines are direct-formula endpoints. Press play to see the sweep. Change test and see the interval change. With x=0x = 0 Wald collapses to a point. Click the figure to fix θ0\theta_0 and read its pp value.

With initial values (x=12x = 12 of n=40n = 40), the score sweep reproduces Wilson interval [0.181, 0.454], with endpoint differences below one ten-thousandth (the grid has 601 points and endpoints are refined by interpolation). Three observations to check. The three intervals invert distinct tests, not approximations to one test; they agree at large nn and diverge otherwise. With x=0x = 0 Wald is the point {0}\{0\}, because estimated standard error is 0: inverting that test yields zero length exactly when uncertainty is greatest. Wilson ([0,0.0876][0, 0.0876] with n=40n = 40) and Clopper–Pearson ([0,0.0881][0, 0.0881]) instead say something useful, on the scale of clinicians’ “rule of three” (3/n=0.0753/n = 0.075, the one-sided 95 % upper bound: 1−0.051/n≈3/n1 - 0.05^{1/n} \approx 3/n). The exact interval is slightly wider than Wilson: the exact pp value is discrete and never touches α\alpha, as in the previous figure, and the interval inherits that conservatism.

What a pp value is not

The American Statistical Association issued a 2016 statement on pp values (Wasserstein and Lazar) following widespread misuse of the 0.05 threshold. Its six principles, paraphrased:

  1. A pp value can indicate how incompatible data are with a specified statistical model.
  2. It does not measure the probability that the hypothesis is true, or that data arose “by chance alone”.
  3. Scientific conclusions and decisions should not rest solely on whether pp crosses a threshold.
  4. Correct inference requires complete, transparent reporting.
  5. A pp value or statistical significance does not measure effect size or result importance.
  6. By itself, a pp value is not a good measure of evidence about a model or hypothesis.

The second is most important and can be quantified. A level-α\alpha test guarantees P(significativo∣H0)≤α\Pr(\text{significativo} \given H_0) \le \alpha. The real question is the inverse, P(H0∣significativo)\Pr(H_0 \given \text{significativo}), and by Bayes’ theorem and conditional probability it cannot be answered without knowing how often tested hypotheses are true and test power. “Significativo” denotes a significant result.

P(H0)=1−π,P(H1)=π\Pr(H_0) = 1 - \pi, \qquad \Pr(H_1) = \pi
π\pi is the fraction of tested hypotheses that are true (there is a real effect). It is a property of the field, not the test.
1/5

This is Ioannidis’ (2005) argument for why so many published findings fail to replicate, and explains behavior of teams testing many ideas with a limited data budget. Try the following lab.

InteractiveWhat fraction of significant findings are false?
1000 hypotheses tested with a two-sided zz test at level α=0.050\alpha = 0.050 and power 0.80 when an effect exists
true findingfalse positiveundetected true effectnull not rejected
10 %
0.80
Level α\alpha
What to count
Hypotheses tested | true1000 | 98
Significant (p≤0.050p \le 0.050)122 (79 true, 43 false)
False positives among these: this batch | formula35 % | 36.0 %
True effects missed19 of 98
More than 3 in 10 “discoveries” are false even though each test has α=0.050\alpha = 0.050. Level α\alpha controls P(reject∣H0)\Pr(\text{reject} \given H_0), not P(H0∣reject)\Pr(H_0 \given \text{reject}).
A virtual lab tests 1000 hypotheses, each true with probability π\pi, using a two-sided zz test. Green circles are real discoveries, red false positives, rings undetected real effects. Leave power at 0.8 and lower π\pi toward 0.01: red eventually dominates although α\alpha is unchanged. Then switch to 'only nearly significant', i.e. 0.8α<p≤α0.8\alpha < p \le \alpha, the band containing the p=0.049p = 0.049 celebrated in many reports. Only about ten hypotheses fall in that band, so each batch is noisy; the formula gives its expected value.

With π=0.1\pi = 0.1 and power 0.8 false positive risk is 36 %; with π=0.01\pi = 0.01 (one true hypothesis in 100) it is 86 %; with π=0.5\pi = 0.5 it falls to 5.9 %. Two more facts the figure shows. Power matters. With π=0.1\pi = 0.1 and power 0.2, not unusual in small studies, risk is 69 %: a low-power test not only misses real effects, but makes a greater fraction of its declarations false. Near the threshold is worse. Among 0.04<p≤0.050.04 < p \le 0.05 results with π=0.1\pi = 0.1 and power 0.8, false positive risk is 77 %, because under a well-powered alternative pp values accumulate near 0, and under the null are uniform: a pp in that band is only 2.7 times likelier under H1H_1 than H0H_0, while H1H_1 began nine times less likely.

You need not be Bayesian to draw the practical lesson: contextualize pp with prior plausibility of the hypothesis and test power; when many hypotheses are tested, error control changes completely, as in multiple comparisons and, for continually inspected data, sequential experiments. For scale: with 20 independent tests of true nulls, the chance of at least one p<0.05p < 0.05 is 1−0.9520=64 %1 - 0.95^{20} = 64\,\%.

Significance versus relevance: demonstrating no relevant effect

A “nonsignificant” result does not prove no effect, and a “significant” one does not prove the effect matters. With n=5120n = 5120 pairs, a 0.6 ms latency difference (standard deviation 12 ms) gives p<0.001p < 0.001; it is real and irrelevant. With n=20n = 20 pairs, a 1.5 ms difference gives p=0.58p = 0.58, without telling us whether latency worsened by 8 ms. Both share a root: the classical test asks “is the effect nonzero?”, rarely the question of interest.

When seeking to demonstrate absence of a relevant effect (the optimized analyzer is not slower, the quantized model does not lose accuracy, the new provider is equivalent), the structure demands reversing roles: if H0H_0 is presumed and the test protects against rejecting it in error, what you want to demonstrate must be H1H_1. Fix an equivalence margin Δ>0\Delta > 0 (smallest important difference, decided for business or domain reasons before the experiment) and test

H0:∣μ∣≥Δfrente aH1:∣μ∣<Δ.H_0 : \abs{\mu} \ge \Delta \qquad \text{frente a} \qquad H_1 : \abs{\mu} < \Delta .
Proof

(a) H0=H01∪H02H_0 = H_{01} \cup H_{02}. If μ∈H01\mu \in H_{01}, rejecting H0H_0 requires rejecting H01H_{01}, with probability at most α\alpha because that test has level α\alpha; similarly for H02H_{02}. This is an intersection–union test (Berger, 1982): the null is a union, rejected only when all components are rejected, so no multiplicity correction is needed. (Do not confuse this with Roy’s union–intersection tests, where the null is an intersection and rejecting one component suffices; those do require correction.) (b) Reject H01H_{01} if (d^+Δ)/SE>t1−α(\hat d + \Delta)/\mathrm{SE} > t_{1-\alpha}, i.e. d^−t1−αSE>−Δ\hat d - t_{1-\alpha}\mathrm{SE} > -\Delta, and H02H_{02} if (Δ−d^)/SE>t1−α(\Delta - \hat d)/\mathrm{SE} > t_{1-\alpha}, i.e. d^+t1−αSE<Δ\hat d + t_{1-\alpha}\mathrm{SE} < \Delta. Both together mean “the interval fits inside the zone”.

∎

Result (b) bridges the previous section and gives a visual rule: to demonstrate equivalence at 5 %, inspect the 90 % interval, not the 95 % interval. (Initially surprising: 5 % is each one-sided test’s level, and each 95 % one-sided interval leaves 5 % in one tail.) The figure shows four combinations of classical and equivalence tests.

InteractiveSignificance versus relevance
Latency difference (ms), its intervals and the equivalence region
no effectequivalence95% CI: includes 0?90% CI: fits in the region?
pp values versus nn (holding d^\hat d, σ\sigma and Δ\Delta fixed)
α = 0.05
  • 95% CI (classical test)
  • 90% CI (TOST)
  • equivalence region
  • classical pp
  • pTOSTp_{\text{TOST}}
Starting cases
1.5 ms
12.0 ms
20
±5.0 ms
Standard error2.68 ms
95% CI | 90% CI[−4.1, 7.1] | [−3.1, 6.1]
Classical pp (H0:μ=0H_0: \mu = 0)0.58 (not significant)
TOST: p1p_1 (μ≤−Δ\mu \le -\Delta) | p2p_2 (μ≥Δ\mu \ge \Delta)0.013 | 0.10
pTOST=max⁡(p1,p2)p_{\text{TOST}} = \max(p_1, p_2)0.10 (not established)
Minimum nn for TOST to conclude (with this d^\hat d and σ\sigma)34
Neither significant nor equivalent: the result is inconclusive. More data are needed; absence of evidence is not evidence of absence.
Latency difference between an optimized and original version (positive = slower), with nn measurement pairs. Green is equivalence zone (−Δ,Δ)(-\Delta, \Delta); blue the 95 % interval (which decides the classical H0:μ=0H_0 : \mu = 0 test); magenta the 90 % interval (which decides TOST). Try four presets: little data, demonstrated equivalence, real but trivial effect, and deterioration. On the log-scale panel, both pp values versus nn with the same observed difference: with small nonzero d^\hat d and large nn, both the classical test and TOST eventually become significant.

Four readings. Little data (n=20n = 20, d^=1.5\hat d = 1.5 ms): neither significant (p=0.58p = 0.58) nor equivalent (pTOST=0.10p_{\text{TOST}} = 0.10); the 90 % interval [−3.1,6.1][-3.1, 6.1] leaves the zone. This is inconclusive, not “no difference”. Equivalence (n=80n = 80, d^=0.3\hat d = 0.3): nonsignificant (p=0.82p = 0.82) and equivalent (pTOST=0.0004p_{\text{TOST}} = 0.0004), the desired claim. Trivial effect (n=5120n = 5120, d^=0.6\hat d = 0.6): significant and equivalent simultaneously; the difference is nonzero and too small to matter. Worsens (n=160n = 160, d^=6\hat d = 6): significant and not equivalent; the classical test works here. Two lessons: high pp does not prove equivalence, and low pp does not prove relevance. Practically, TOST concludes only if standard error is small relative to Δ\Delta, and the figure computes the minimum nn for each case (34 pairs in the first, with the same d^=1.5\hat d = 1.5 and σ=12\sigma = 12).

Two technical points. First, TOST has size α\alpha only in the limit: when SE\mathrm{SE} is large relative to Δ\Delta, actual probability of declaring equivalence at the boundary is well below α\alpha (the test is conservative and nearly powerless). Second, margin Δ\Delta is a substantive, not statistical, choice: justify it using domain reasons and fix it before seeing data. Lakens, Scheel and Isager (2018) call it the smallest effect size of interest. If only one direction matters (the new version is not worse by more than Δ\Delta), a single one-sided test against Δ\Delta suffices: noninferiority.

Tests from scratch

Implement one-sample tests with minimal tools: the normal tail via math.erfc and the tt tail via regularized incomplete beta (the formula P(T≥t)=12Iν/(ν+t2)(ν/2,1/2)\Pr(T \ge t) = \tfrac12 I_{\nu/(\nu + t^2)}(\nu/2, 1/2) for t≥0t \ge 0). Then compare them with scipy.stats.

[ ]One-sample z and t tests from scratchBrowser
import math
import numpy as np
from scipy import special, stats

def cola_normal(z):
    """P(Z >= z) para Z ~ N(0, 1)."""
    return 0.5 * math.erfc(z / math.sqrt(2.0))

def cola_t(t, gl):
    """P(T >= t) para T ~ t de Student con gl grados de libertad."""
    c = 0.5 * special.betainc(gl / 2.0, 0.5, gl / (gl + t * t))
    return c if t >= 0 else 1.0 - c

def valor_p(cola, estadistico, alternativa):
    """Valor p a partir de la función de cola; alternativa: 'mayor', 'menor' o 'bilateral'."""
    if alternativa == "mayor":
        return cola(estadistico)
    if alternativa == "menor":
        return cola(-estadistico)
    return min(1.0, 2.0 * cola(abs(estadistico)))

def contraste_z(x, mu0, sigma, alternativa="bilateral"):
    z = math.sqrt(len(x)) * (np.mean(x) - mu0) / sigma
    return z, valor_p(cola_normal, z, alternativa)

def contraste_t(x, mu0, alternativa="bilateral"):
    n = len(x)
    t = math.sqrt(n) * (np.mean(x) - mu0) / np.std(x, ddof=1)
    return t, valor_p(lambda u: cola_t(u, n - 1), t, alternativa)

# los datos de la motivación (la celda anterior sigue viva en la sesión)
for alt in ("bilateral", "mayor", "menor"):
    t, p = contraste_t(d, 0.0, alt)
    ref = stats.ttest_1samp(d, 0.0, alternative={"bilateral": "two-sided", "mayor": "greater", "menor": "less"}[alt])
    print(f"{alt:>9}: t = {t:.4f}  p propio = {p:.6f}   scipy = {ref.pvalue:.6f}")
print("con sigma = 4 conocida:", tuple(round(v, 4) for v in contraste_z(d, 0.0, 4.0)))

Each test is a statistic plus the tail of its null distribution. All three pp values agree with scipy in every digit: the right-sided value is half the two-sided value because tt is symmetric, and the left-sided value is its complement. Now simulation checks whether tests deliver their promises: type I error rate and pp-value uniformity under true H0H_0. Include an incorrect test using sample deviation SS but a normal rather than tt quantile (a widespread mistake), and centered exponential data, violating normality.

[ ]Type I error rate and p-value uniformityBrowser
import matplotlib.pyplot as plt

rng = np.random.default_rng(10)
R = 20000
print("   n   t con normales   'z con S' (error)   t con datos exponenciales")
for n in (5, 10, 30):
    x = rng.normal(0, 1, (R, n))                       # H0 cierta: media 0
    t = np.sqrt(n) * x.mean(1) / x.std(1, ddof=1)
    p_t = 2 * stats.t.sf(np.abs(t), n - 1)
    p_z = 2 * stats.norm.sf(np.abs(t))
    e = rng.exponential(1.0, (R, n)) - 1.0             # H0 cierta: media 0, asimétrica
    te = np.sqrt(n) * e.mean(1) / e.std(1, ddof=1)
    p_e = 2 * stats.t.sf(np.abs(te), n - 1)
    print(f"{n:>4}   {np.mean(p_t <= .05):>14.4f}   {np.mean(p_z <= .05):>17.4f}   {np.mean(p_e <= .05):>25.4f}")
    if n == 10:
        p_t10, p_z10 = p_t, p_z

fig, ax = plt.subplots(1, 2, figsize=(9, 3.2), sharey=True)
ax[0].hist(p_t10, bins=20, range=(0, 1), density=True)
ax[0].set_title("t correcto, n = 10")
ax[1].hist(p_z10, bins=20, range=(0, 1), density=True, color="C3")
ax[1].set_title("'z con S', n = 10")
for a in ax:
    a.axhline(1, color="gray", ls="--")
    a.set_xlabel("valor p")
plt.show()

The correct tt test rejects 5 % of the time for any nn and its histogram is flat. Using SS with a normal quantile inflates error: 11.9 % at n=5n = 5 and 8.1 % at n=10n = 10, with too many small histogram values. Even the correct test on skewed data has actual size 9.8 % at n=10n = 10: the tn−1t_{n-1} null assumes normality, and approaches nominal slowly as nn grows. A test’s guarantee is only as good as its null distribution.

Finally, duality. Instead of xˉ±t s/n\bar x \pm t\,s/\sqrt n, find endpoints of the μ0\mu_0 region the test does not reject by solving p(μ0)=αp(\mu_0) = \alpha with a root method.

[ ]From test to interval: invert the t testBrowser
from scipy.optimize import brentq

n, xbar, s = len(d), d.mean(), d.std(ddof=1)

def p_bilateral(mu0):
    return valor_p(lambda u: cola_t(u, n - 1), np.sqrt(n) * (xbar - mu0) / s, "bilateral")

alfa = 0.05
inf = brentq(lambda m: p_bilateral(m) - alfa, xbar - 10 * s, xbar)
sup = brentq(lambda m: p_bilateral(m) - alfa, xbar, xbar + 10 * s)
tcrit = stats.t.ppf(1 - alfa / 2, n - 1)
print(f"intervalo por inversión: [{inf:.6f}, {sup:.6f}]")
print(f"fórmula xbar ± t s/√n:   [{xbar - tcrit * s / np.sqrt(n):.6f}, {xbar + tcrit * s / np.sqrt(n):.6f}]")

rejilla = np.linspace(xbar - 3 * s, xbar + 3 * s, 2001)
no_rech = rejilla[[p_bilateral(m) > alfa for m in rejilla]]
print(f"rejilla de 2001 valores: no se rechazan los de [{no_rech.min():.3f}, {no_rech.max():.3f}]")
print(f"¿se rechaza mu0 = 0 al 5 %?  p = {p_bilateral(0.0):.4f}  ->  0 {'está fuera' if p_bilateral(0.0) <= alfa else 'está dentro'} del intervalo")

The endpoints obtained as pp-value roots agree with the tt interval formula to all digits, and the grid stepping by 0.011 in μ0\mu_0 finds them to that precision. This numerically demonstrates duality: the closed-form interval solves p(μ0)=αp(\mu_0) = \alpha for the tt test. Since 00 is inside [−0.19,2.22][-0.19, 2.22], the two-sided 5 % test does not reject μ0=0\mu_0 = 0, consistent with p=0.0975p = 0.0975.

TOST: demonstrating an optimization does not worsen latency

Second lab. We optimized the analyzer and want to show its latency differs from the original by no more than Δ=3\Delta = 3 ms. Measure two independent groups and compare classical test and TOST on the same data. Data have true difference 0.4 ms and standard deviation 6 ms.

[ ]TOST from scratch: the error of concluding no difference from high pBrowser
def tost_ind(x1, x2, bajo, alto):
    """TOST con dos muestras independientes y varianza común.
    Devuelve (p_tost, p1, p2, diferencia, error estándar, grados de libertad)."""
    n1, n2 = len(x1), len(x2)
    gl = n1 + n2 - 2
    dif = x1.mean() - x2.mean()
    sp2 = ((n1 - 1) * x1.var(ddof=1) + (n2 - 1) * x2.var(ddof=1)) / gl
    se = np.sqrt(sp2 * (1 / n1 + 1 / n2))
    p1 = cola_t((dif - bajo) / se, gl)          # H01: dif <= bajo
    p2 = cola_t((alto - dif) / se, gl)          # H02: dif >= alto
    return max(p1, p2), p1, p2, dif, se, gl

def datos(n, semilla, dif=0.4, sd=6.0):
    r = np.random.default_rng(semilla)
    return r.normal(100 + dif, sd, n), r.normal(100, sd, n)

print(" n por grupo   diferencia   p clásico   p TOST   ¿equivalentes (margen ±3 ms)?")
for n, semilla in [(8, 7), (80, 5), (20000, 3)]:
    a, b = datos(n, semilla)
    p_clasico = stats.ttest_ind(a, b).pvalue
    p_tost = tost_ind(a, b, -3.0, 3.0)[0]
    print(f"{n:>11}   {a.mean() - b.mean():>10.3f}   {p_clasico:>9.4g}   {p_tost:>6.4f}   {'sí' if p_tost <= 0.05 else 'no demostrado'}")

# la equivalencia es el intervalo del 90 %: comprobación para n = 80
a, b = datos(80, 5)
p, p1, p2, dif, se, gl = tost_ind(a, b, -3.0, 3.0)
tc = stats.t.ppf(0.95, gl)
print(f"\nn = 80: IC 90 % = [{dif - tc * se:.3f}, {dif + tc * se:.3f}] dentro de (-3, 3): {-3 < dif - tc * se and dif + tc * se < 3};  p_TOST = {p:.4f}")

Look at the first two rows. With 8 observations per group the difference is tiny and classical pp huge, but TOST cannot demonstrate equivalence: the interval is too wide to fit in (−3,3)(-3, 3). With 80 per group classical pp remains high and equivalence is now demonstrated (pTOST=0.0012p_{\text{TOST}} = 0.0012). The third row is the reverse: 20 000 per group detect a real difference of a few tenths of a millisecond (significant) and demonstrate it is irrelevant (equivalent). High pp alone cannot distinguish the first two rows.

We still need to check level. If the true difference lies exactly on the boundary (μ=Δ\mu = \Delta), TOST must declare equivalence with probability at most α\alpha, and far below it when σ\sigma is large relative to Δ\Delta.

[ ]TOST level at the H0 boundary and comparison with statsmodelsBrowser
from statsmodels.stats.weightstats import ttost_ind

def tasa_tost(n, sd, dif_real, R=4000, semilla=0):
    r = np.random.default_rng(semilla)
    a = r.normal(dif_real, sd, (R, n))
    b = r.normal(0.0, sd, (R, n))
    gl = 2 * n - 2
    sp2 = (a.var(1, ddof=1) + b.var(1, ddof=1)) / 2
    se = np.sqrt(sp2 * 2 / n)
    dif = a.mean(1) - b.mean(1)
    p = np.maximum(stats.t.sf((dif + 3) / se, gl), stats.t.sf((3 - dif) / se, gl))
    return np.mean(p <= 0.05)

print("tasa de equivalencia declarada con diferencia real = 3 ms (frontera, H0 cierta):")
for n, sd in [(30, 3.0), (30, 6.0), (30, 12.0), (2000, 6.0)]:
    print(f"  n = {n:>4} por grupo, sd = {sd}:  {tasa_tost(n, sd, 3.0):.4f}")

a, b = datos(80, 5)
sm = ttost_ind(a, b, -3.0, 3.0)
mio = tost_ind(a, b, -3.0, 3.0)
print(f"\nstatsmodels: p_TOST = {sm[0]:.6f} (p1 = {sm[1][1]:.6f}, p2 = {sm[2][1]:.2e})")
print(f"desde cero:  p_TOST = {mio[0]:.6f} (p1 = {mio[1]:.6f}, p2 = {mio[2]:.2e})")

With true difference at the boundary, H0H_0 is true and the rate of declared equivalence must not exceed 5 %. With small standard error relative to Δ\Delta the rate approaches 5 % (0.0535 with SE≈0.77\mathrm{SE} \approx 0.77 ms and 0.0493 with SE≈0.19\mathrm{SE} \approx 0.19 ms, both within Monte Carlo error of about ±0.007\pm 0.007); with σ=6\sigma = 6 and 30 observations per group it falls to 3.9 %, and with σ=12\sigma = 12 (SE≈3.1\mathrm{SE} \approx 3.1 ms, on the order of Δ\Delta) it is exactly 0: the 90 % interval is wider than 2Δ2\Delta and cannot fit inside (−3,3)(-3, 3). The test remains level α\alpha, but has no power. statsmodels agrees with our implementation.

Using libraries: scipy.stats and statsmodels

In practice nobody implements the tt test. What matters is knowing what choices each function hides. An instructive case is the exact binomial test’s two-sided pp value, because an asymmetric distribution has no unique definition of “both tails”.

[ ]Exact binomial test: two definitions of the two-sided p-valueBrowser
from scipy.stats import binomtest, binom
from statsmodels.stats.proportion import proportion_confint

def p_duplicado(x, n, p0):
    """Duplica la cola más pequeña: la definición cuya inversión da Clopper-Pearson."""
    return min(1.0, 2 * min(binom.cdf(x, n, p0), binom.sf(x - 1, n, p0)))

print("   x   n    p0   scipy (minlike)   duplicando la cola")
for x, n, p0 in [(3, 20, 0.4), (2, 20, 0.3), (14, 40, 0.3), (9, 12, 0.5)]:
    print(f"{x:>4} {n:>3} {p0:>5}   {binomtest(x, n, p0).pvalue:>15.4f}   {p_duplicado(x, n, p0):>17.4f}")

bt = binomtest(12, 40, 0.5)
print("\nIC 95 % de 12 éxitos en 40 ensayos:")
print("  scipy exact          :", np.round(tuple(bt.proportion_ci(0.95, method="exact")), 4))
print("  statsmodels 'beta'   :", np.round(proportion_confint(12, 40, 0.05, method="beta"), 4), "(Clopper-Pearson)")
print("  scipy wilson         :", np.round(tuple(bt.proportion_ci(0.95, method="wilson")), 4))
print("  statsmodels 'normal' :", np.round(proportion_confint(12, 40, 0.05, method="normal"), 4), "(Wald)")

scipy.stats.binomtest computes the two-sided pp value by summing probabilities of outcomes no more likely than observed (minimum-likelihood criterion), unlike doubling the smaller tail. At x=3x = 3, n=20n = 20, θ0=0.4\theta_0 = 0.4 the values are 0.0224 and 0.0319, and the 3 % decision changes with definition. Its exact interval (method="exact") is Clopper–Pearson, the inversion of the doubled-tail version (hence agreement with proportion_confint(method="beta")), not minimum likelihood. A summary of library functions:

Taskscipy.statsstatsmodels
One-sample tt, one- or two-sidedttest_1samp(x, mu0, alternative=...)DescrStatsW(x).ttest_mean(mu0, alternative=...)
Two-sample ttttest_ind(a, b, equal_var=...)ttest_ind in stats.weightstats
Proportion test and CIbinomtest(k, n, p0).proportion_ci(method=...)proportion_confint(k, n, method=...)
Equivalenceno direct functionttost_ind, ttost_paired

Common mistakes

Exercises

ProofUniformity of the p-value
Prove: If H0:θ=θ0H_0 : \theta = \theta_0 is simple, large TT values lead to rejection, and the distribution function FF of TT under θ0\theta_0 is continuous, then the pp value is uniform on (0,1)(0, 1) under H0H_0.
0
Let p(X)=Pθ0(T≥t)∣t=T(X)p(X) = \Pr_{\theta_0}(T \ge t)\big|_{t = T(X)} be the observed pp value, and u∈(0,1)u \in (0, 1) a fixed level.

Step 1 of 4. How do you express p(X)p(X) in terms of FF and T=T(X)T = T(X)?

QuizSix statements about p = 0.03
An A/B experiment tests H0H_0: 'the new version does not change conversion rate' and gives p=0.03p = 0.03 (two-sided test, continuous statistic). Which statements are correct?

More than one answer may be correct.

NumericFalse positives among significant results
A team tests many hypotheses, 10 % of which are true. Each is tested at level α=0.05\alpha = 0.05 with power 0.8 when there is an effect. What proportion of results with p≤0.05p \le 0.05 are false positives? Give a fraction between 0 and 1.
CodeInvert the exact binomial test
Complete intervalo_invertido(x, n, alfa) to return the level-1−α1 - \alpha confidence interval for a proportion obtained by inverting the two-sided exact test (doubling the smaller tail, already implemented in pvalor_exacto): the set of p0∈[0,1]p_0 \in [0, 1] with p-valor(p0)>αp\text{-valor}(p_0) > \alpha. Do not use the beta formula: find endpoints by bisection on the pp value. Then verify agreement with Clopper–Pearson, beta.ppf(alfa/2, x, n - x + 1) and beta.ppf(1 - alfa/2, x + 1, n - x).
import numpy as np
from scipy.stats import binom

def pvalor_exacto(x, n, p0):
  """P-valor bilateral exacto de H0: p = p0, duplicando la cola más pequeña (máximo 1)."""
  return min(1.0, 2 * min(binom.cdf(x, n, p0), binom.sf(x - 1, n, p0)))

def intervalo_invertido(x, n, alfa=0.05, tol=1e-10):
  """Devuelve (inferior, superior): los p0 en [0, 1] que el test NO rechaza al nivel alfa."""
  # tu código: bisección en [0, x/n] para el extremo inferior y en [x/n, 1] para el superior
  return 0.0, 1.0
Shift+Enter to run
QuizThe right test for each question
Choose a test for three product-team decisions. (A) 'We deploy the new triage model only if detection improves; otherwise keep the current one.' (B) 'We are changing inference provider: any mean latency change matters, faster (savings) or slower (redesign).' (C) 'We want to show the new cache library is equally fast, within 5 ms.' Which assignment is correct?
NumericType II error of a z test
With Xi∼iidN(μ,1)X_i \iid \Normal(\mu, 1), n=25n = 25, test H0:μ=0H_0 : \mu = 0 versus H1:μ>0H_1 : \mu > 0 at level α=0.05\alpha = 0.05 by rejecting if n Xˉ≥1.645\sqrt n\,\bar X \ge 1.645. If the true mean is μ=0.5\mu = 0.5, what is β\beta, the probability of a type II error?
NumericTOST p-value
With a large sample (normal approximation), observed latency difference is d^=1\hat d = 1 ms with standard error SE=1.5\mathrm{SE} = 1.5 ms, and equivalence margin Δ=5\Delta = 5 ms. What is pTOST=max⁡(p1,p2)p_{\text{TOST}} = \max(p_1, p_2)?

Summary

Key idea
A test is a decision rule whose level α\alpha controls type I error, and the pp value (uniform under the null) is the smallest level at which rejection occurs; confidence intervals invert these tests. But pp is not the probability of H0H_0 (which depends on prior plausibility and power), does not measure effect size, and high pp does not prove absence of effect: that requires an equivalence test with a prespecified margin.