DEV Community

Nylah Reynard
Nylah Reynard

Posted on

Why Your Python t-Test Disagrees With R (And Why Levene Pre-Testing Fails)

#r

I spent three hours last week debugging what looked like impossible math in our experiment pipeline. An R analysis flagged a two-sample feature rollout as inconclusive with p = 0.0866. My Python reimplementation, running against the exact same database extract, declared a statistically significant victory with p = 0.00102.

The observations were identical and group means matched to four decimals, yet R's t.test and Python's scipy.stats.ttest_ind gave opposite verdicts. This discrepancy comes from a thirty-year divergence in library defaults, combined with textbook statistical advice that collapses on real data.


The bug was not in the database query. It was in how each environment handles group variance.

When you call t.test(a, b) in R, stats defaults to var.equal = FALSE. R runs Welch's t-test, using the Welch–Satterthwaite equation to adjust degrees of freedom downward for unequal variance.

Passing two arrays straight to ttest_ind in scipy.stats leaves equal_var=True active by default. It runs Student's pooled-variance t-test, pooling sample variances and fixing degrees of freedom at n1 + n2 - 2.

Here is the minimal reproduction, verified locally on Python 3.14.3 with NumPy 2.4.4 and SciPy 1.17.1:

import numpy as np
from scipy import stats

a = np.array([14.2, 8.1, 19.5, 6.4, 15.8, 21.0, 9.3, 17.6, 5.9, 18.4, 11.2, 22.1])
b = np.array([
    10.8, 11.4, 10.2, 11.9, 10.5, 11.1, 10.9, 11.6, 10.4, 11.3,
    10.7, 11.5, 10.6, 11.2, 10.3, 11.8, 10.9, 11.0, 10.5, 11.4,
    10.8, 11.1, 10.7, 11.3, 10.6, 11.2, 10.9, 11.5, 10.4, 11.0,
    10.8, 11.2, 10.7, 11.1, 10.9, 11.3, 10.5, 11.4, 10.8, 11.0,
])

student = stats.ttest_ind(a, b)
welch = stats.ttest_ind(a, b, equal_var=False)

print(f"Student: t = {student.statistic:.4f}, df = {student.df:.2f}, p = {student.pvalue:.5f}")
print(f"Welch:   t = {welch.statistic:.4f}, df = {welch.df:.2f}, p = {welch.pvalue:.5f}")
Enter fullscreen mode Exit fullscreen mode

Running this script outputs:

Student: t = 3.4892, df = 50.00, p = 0.00102
Welch:   t = 1.8812, df = 11.03, p = 0.08658
Enter fullscreen mode Exit fullscreen mode

Group a has n = 12, mean 14.125, and standard deviation 5.787. Group b has n = 40, mean 10.980, and standard deviation 0.411. Group a is small and noisy; group b is large and tight.

Student's pooled test weights variances by sample size. Because group b has 40 observations with tiny variance, the pooled variance collapses. Student's test assigns 50 degrees of freedom, producing an inflated t = 3.4892 with p = 0.00102—fabricating significance from sample size imbalance.

Welch's t-test never pools variances. It divides each sample variance by its own sample size. Because the noisy group has only 12 points, the Welch–Satterthwaite formula cuts degrees of freedom from 50 to 11.03, yielding t = 1.8812 with p = 0.08658. The effect was never significant.


Engineers often ask: why not run Levene's test first? If Levene's test rejects equal variances at p < 0.05, switch to Welch; otherwise stick with Student. This two-stage workflow is taught in almost every undergraduate stats class. It is also mathematically broken.

Marie Delacre, Daniël Lakens, and Christophe Leys demonstrated why in a 2017 paper in the International Review of Social Psychology (volume 30, issue 1, pages 92-101). When sample sizes and variances are both unequal, Student's t-test severely inflates Type I error. Yet in small or moderate samples, Levene's pre-test lacks statistical power to detect the disparity. The pre-test fails to sound the alarm precisely when Student's test is most dangerous.

To verify this, I ran a 20,000-trial simulation under the null hypothesis (mean 0.0 for both groups, nominal alpha = 0.05) using rng = np.random.default_rng(20261123):

import numpy as np
from scipy import stats

n_trials = 20000

# Condition 1: n1=20, sd1=3.0 vs n2=80, sd2=1.0
rng = np.random.default_rng(20261123)
x1 = rng.normal(0.0, 3.0, size=(n_trials, 20))
x2 = rng.normal(0.0, 1.0, size=(n_trials, 80))

p_student_1 = stats.ttest_ind(x1, x2, axis=1, equal_var=True).pvalue
p_welch_1 = stats.ttest_ind(x1, x2, axis=1, equal_var=False).pvalue

fp_s1 = np.mean(p_student_1 < 0.05)
fp_w1 = np.mean(p_welch_1 < 0.05)

print("Condition 1 (n1=20, sd1=3.0 vs n2=80, sd2=1.0):")
print(f"  Student (equal_var=True):  {fp_s1:.4f} ({fp_s1 * 100:.2f}% false positive rate)")
print(f"  Welch (equal_var=False):   {fp_w1:.4f} ({fp_w1 * 100:.2f}% false positive rate)")
print()

# Condition 2: n1=12, sd1=2.0 vs n2=36, sd2=1.0 with Levene pre-test
rng = np.random.default_rng(20261123)
x1 = rng.normal(0.0, 2.0, size=(n_trials, 12))
x2 = rng.normal(0.0, 1.0, size=(n_trials, 36))

p_student_2 = stats.ttest_ind(x1, x2, axis=1, equal_var=True).pvalue
p_welch_2 = stats.ttest_ind(x1, x2, axis=1, equal_var=False).pvalue

lev = np.array([stats.levene(x1[i], x2[i], center="median").pvalue < 0.05 for i in range(n_trials)])
p_2stage = np.where(lev, p_welch_2, p_student_2)

fp_s2 = np.mean(p_student_2 < 0.05)
fp_2stage = np.mean(p_2stage < 0.05)
lev_power = np.mean(lev)
fp_w2 = np.mean(p_welch_2 < 0.05)

print("Condition 2 (n1=12, sd1=2.0 vs n2=36, sd2=1.0):")
print(f"  Student (equal_var=True):  {fp_s2:.4f} ({fp_s2 * 100:.2f}% false positive rate)")
print(f"  Two-stage Levene screen:   {fp_2stage:.4f} ({fp_2stage * 100:.2f}% false positive rate)")
print(f"  Levene detection power:    {lev_power:.4f} ({lev_power * 100:.2f}%)")
print(f"  Welch (equal_var=False):   {fp_w2:.4f} ({fp_w2 * 100:.2f}% false positive rate)")
Enter fullscreen mode Exit fullscreen mode

The empirical results reveal why conditional pre-testing leaks false positives:

Condition 1 (n1=20, sd1=3.0 vs n2=80, sd2=1.0):
  Student (equal_var=True):  0.2498 (24.98% false positive rate)
  Welch (equal_var=False):   0.0497 (4.97% false positive rate)

Condition 2 (n1=12, sd1=2.0 vs n2=36, sd2=1.0):
  Student (equal_var=True):  0.1525 (15.25% false positive rate)
  Two-stage Levene screen:   0.0771 (7.71% false positive rate)
  Levene detection power:    0.6933 (69.33%)
  Welch (equal_var=False):   0.0495 (4.95% false positive rate)
Enter fullscreen mode Exit fullscreen mode

In Condition 1, where the smaller cohort has threefold larger variance, Student's default t-test rejects the null in 24.98% of neutral experiments instead of 5%. One in four neutral rollouts is flagged as a false win. Welch's t-test maintains nominal error control at 4.97%.

In Condition 2, Levene's median-centered test detects the imbalance only 69.33% of the time. The remaining 30.67% falls back to Student's test, leaking a 7.71% false-positive rate. Unconditional Welch holds at 4.95%.


There is a critical boundary condition here, highlighted in the authors' 2022 Corrigendum (International Review of Social Psychology, volume 35, issue 1, page 21, DOI 10.5334/irsp.661).

In their 2017 paper, the authors noted that Welch and Student t-tests yield identical test statistics when sample variances are equal. The 2022 Corrigendum clarifies that Student and Welch t-statistics match only when both sample sizes and sample standard deviations are simultaneously equal (n1 == n2 and s1 == s2). Under unequal group sizes, the degrees of freedom calculation diverges even if sample standard deviations match.

The Corrigendum also clarifies that while Welch's t-test protects Type I error across unequal variances without power loss under equal variances, it does not resolve severe skewness or extreme outliers. For heavily skewed distributions, trimmed-mean methods like Yuen's test remain necessary.


If you maintain experimentation pipelines in Python, take three concrete steps:

First, audit all scipy.stats.ttest_ind calls. If equal_var=False is missing, your service defaults to Student's pooled test and will inflate false positives whenever cohort sizes and variances differ.

Second, retire two-stage Levene pre-tests. Defaulting unconditionally to Welch's t-test costs negligible statistical power under true homoscedasticity while eliminating the Type I error leakage of failed pre-tests.

Third, log fractional Welch–Satterthwaite degrees of freedom. Seeing df = 11.03 confirms to auditors that the test corrected for unequal group variances.

Make equal_var=False your non-negotiable default. Production decisions should never depend on accidental homoscedasticity.

Top comments (0)