Compute P-Values for Statistical Hypothesis Tests
Arrays & HashingAuto-graded · 25 test casesLast updated
Tests numerical stability in tail probability calculation, distribution function implementation, and handling of hypothesis testing edge cases.
Write a function that computes p-values for statistical hypothesis tests using either the standard normal (z) or Student's t distribution.
Your function must accept four parameters:
test_statistic(float): The computed test statisticalternative_hypothesis(str): One of'less','greater', or'two-sided'distribution(str): Either'z'(standard normal) or't'(Student's t)degrees_of_freedom(float, optional): Required whendistribution='t'; must be ≥ 1
Return Value
Return the p-value as a float, or None for invalid inputs.
P-value Definition
The p-value is calculated as follows:
- 'greater': P(X > test_statistic), the probability that a random variable from the specified distribution exceeds the test statistic
- 'less': P(X < test_statistic), the probability that a random variable is less than the test statistic
- 'two-sided': For symmetric distributions, this is 2 × min(P(X > |test_statistic|), P(X < -|test_statistic|)), which equals 2 × P(X > |test_statistic|), capped at 1.0
Both the standard normal and Student's t distributions are symmetric around zero.
Requirements
For the standard normal distribution ('z'):
- Implement the cumulative distribution function using
math.erformath.erfc - Do not use external statistical libraries (like scipy) for the normal distribution
- Your implementation must achieve relative error ≤ 1e-9 for |test_statistic| ≤ 8
- Use numerically stable methods that compute tail probabilities directly, never as
1 - cdf(x), to avoid catastrophic cancellation
For the t distribution ('t'):
- You may use
scipy.stats.tif available - If scipy is unavailable, implement an approximation using the incomplete beta function
- The relationship is: P(T > t) = ½ · I_x(ν/2, ½) where x = ν/(ν + t²) for t ≥ 0
Edge Cases
- Return
Noneiftest_statisticis NaN - Return
Noneifdistribution='t'anddegrees_of_freedomis None, NaN, or < 1 - If
test_statisticis +∞: return 0.0 for 'greater' and 'two-sided', return 1.0 for 'less' - If
test_statisticis -∞: return 1.0 for 'greater', return 0.0 for 'less' and 'two-sided' - Treat infinite degrees of freedom as equivalent to the standard normal distribution
- Clamp all finite results to the range [0, 1]
- Raise
ValueErrorfor invalidalternative_hypothesisordistributionvalues
Constraints
- -10⁹ ≤ test_statistic ≤ 10⁹ (when finite)
- alternative_hypothesis ∈ {'less', 'greater', 'two-sided'}
- distribution ∈ {'z', 't'}
- 1 ≤ degrees_of_freedom ≤ 10⁶ (when finite and valid)
Examples
Example 1
Input: compute_p_value(0, 'two-sided', 'z')
Output: 1
Example 2
Input: compute_p_value(1.96, 'two-sided', 'z')
Output: 0.04999579029644087
Example 3
Input: compute_p_value(5, 'greater', 'z')
Output: 2.866515718791946e-7
Example 4
Input: compute_p_value(2, 'two-sided', 't', 10)
Output: 0.07338803477074024
Hints
Hint 1
Always compute tail probabilities directly using the survival function, never as 1 - CDF, to avoid catastrophic cancellation when probabilities are very close to 1.
Hint 2
For the normal distribution, use erfc(z/√2)/2 to compute the upper tail P(Z > z). The two-sided p-value can be computed as erfc(|z|/√2) without an additional doubling step.
Hint 3
Both distributions are symmetric around zero. Use this property: P(X < -s) = P(X > s), so you can compute the 'less' alternative by negating the statistic and computing the 'greater' alternative.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core principle is to compute all tail probabilities directly using the survival function (upper-tail probability) rather than subtracting the CDF from 1. When a CDF value is very close to 1 (within machine epsilon), computing 1 - cdf suffers from catastrophic cancellation and returns zero or numerical noise instead of the true small probability.
Define the survival function as S(x) = P(X > x). Then:
- 'greater' alternative: directly return
S(test_statistic) - 'less' alternative: exploit symmetry to return
S(-test_statistic), since both distributions are symmetric around zero - 'two-sided' alternative: return
2·S(|test_statistic|), capped at 1.0
Standard Normal Distribution
For the z-distribution, use the complementary error function:
S(z) = P(Z > z) = ½ · erfc(z / √2)
The function math.erfc is implemented with no cancellation issues and maintains accuracy even for large positive arguments where it returns values as small as 10⁻³⁰⁰.
For the two-sided case, we can use the identity erfc(|z| / √2) = 2·S(|z|) directly, which avoids an unnecessary multiplication.
Student's t Distribution
The upper tail of the t-distribution can be expressed using the regularized incomplete beta function:
P(T > t) = ½ · I_x(ν/2, ½)
where x = ν/(ν + t²) for t ≥ 0
If scipy is available, use scipy.stats.t.sf which computes the survival function directly. Otherwise, implement the incomplete beta using a continued fraction (modified Lentz algorithm).
Key numerical tricks:
- Compute
1 - x = t²/(ν + t²)directly rather than subtracting, preserving precision when x is close to 1 - Use log-space for the beta function prefactor to avoid overflow:
exp(lgamma(a+b) - lgamma(a) - lgamma(b) + a·log(x) + b·log(1-x)) - When x > (a+1)/(a+b+2), use the reflection formula
I_x(a,b) = 1 - I_{1-x}(b,a)to ensure the continued fraction converges quickly
Edge Cases
- NaN test statistics return
None - Infinite test statistics return exact 0.0 or 1.0 based on direction and alternative
- For t-distribution: invalid or missing degrees of freedom return
None - Infinite degrees of freedom is treated as the standard normal
- All results are clamped to [0, 1]
Why It Is Correct
Both the standard normal and Student's t distributions are symmetric around zero, meaning P(X < -s) = P(X > s). This allows us to compute any tail probability using the upper-tail function.
The two-sided p-value represents the probability of observing a value at least as extreme in either direction. For a symmetric distribution, this is 2 × P(X > |test_statistic|), which we cap at 1.0 to handle the edge case when the test statistic is zero.
The continued fraction approach for the incomplete beta function is the standard numerical method used in statistical libraries, providing accurate results with controlled convergence.
Complexity
- Time: O(1) for z-distribution. For t-distribution, O(√ν) continued fraction iterations in worst case, typically under 100 for ν ≤ 1000.
- Space: O(1) for both distributions.
Solution
import math
from typing import Optional
try:
from scipy.stats import t as _scipy_t_dist
except ImportError:
_scipy_t_dist = None
_SQRT_TWO = math.sqrt(2.0)
_EPSILON = 1e-15
_TINY = 1e-300
_MAX_ITERATIONS = 10000
def _continued_fraction_beta(a, b, x):
"""Evaluate continued fraction for incomplete beta function using modified Lentz method."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
d = 1.0 / (d if abs(d) > _TINY else _TINY)
h = d
for m in range(1, _MAX_ITERATIONS + 1):
m2 = 2 * m
numerator = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + numerator * d
d = _TINY if abs(d) < _TINY else d
c = 1.0 + numerator / c
c = _TINY if abs(c) < _TINY else c
d = 1.0 / d
h *= d * c
numerator = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + numerator * d
d = _TINY if abs(d) < _TINY else d
c = 1.0 + numerator / c
c = _TINY if abs(c) < _TINY else c
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < _EPSILON:
return h
raise ArithmeticError("Continued fraction did not converge")
def _incomplete_beta_regularized(a, b, x, y):
"""Compute regularized incomplete beta I_x(a,b) where y = 1-x."""
if x <= 0.0:
return 0.0
if y <= 0.0:
return 1.0
log_prefix = (math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y))
if x < (a + 1.0) / (a + b + 2.0):
prefix = math.exp(log_prefix)
return prefix * _continued_fraction_beta(a, b, x) / a
else:
prefix = math.exp(log_prefix)
return 1.0 - prefix * _continued_fraction_beta(b, a, y) / b
def _t_upper_tail_fallback(statistic, df):
"""Compute P(T > statistic) for Student's t using incomplete beta."""
denominator = df + statistic * statistic
x_param = df / denominator
y_param = statistic * statistic / denominator
half_tail = 0.5 * _incomplete_beta_regularized(df / 2.0, 0.5, x_param, y_param)
return half_tail if statistic >= 0 else 1.0 - half_tail
def _upper_tail_probability(statistic, distribution, df):
"""Compute P(X > statistic) directly without cancellation."""
if math.isinf(statistic):
return 0.0 if statistic > 0 else 1.0
if distribution == 'z':
return 0.5 * math.erfc(statistic / _SQRT_TWO)
if _scipy_t_dist is not None:
return float(_scipy_t_dist.sf(statistic, df))
return _t_upper_tail_fallback(statistic, df)
def compute_p_value(test_statistic: float, alternative_hypothesis: str, distribution: str, degrees_of_freedom: Optional[float] = None) -> Optional[float]:
if alternative_hypothesis not in ('less', 'greater', 'two-sided'):
raise ValueError(f"Invalid alternative_hypothesis: {alternative_hypothesis}")
if distribution not in ('z', 't'):
raise ValueError(f"Invalid distribution: {distribution}")
if distribution == 't':
if degrees_of_freedom is None or math.isnan(degrees_of_freedom) or degrees_of_freedom < 1:
return None
if math.isinf(degrees_of_freedom):
distribution = 'z'
if math.isnan(test_statistic):
return None
if alternative_hypothesis == 'greater':
p = _upper_tail_probability(test_statistic, distribution, degrees_of_freedom)
elif alternative_hypothesis == 'less':
p = _upper_tail_probability(-test_statistic, distribution, degrees_of_freedom)
elif distribution == 'z' and not math.isinf(test_statistic):
p = math.erfc(abs(test_statistic) / _SQRT_TWO)
else:
p = 2.0 * _upper_tail_probability(abs(test_statistic), distribution, degrees_of_freedom)
return min(1.0, max(0.0, p))