Coding questions · Roblox
Implement Python Function for Statistical Test P-Values
This question evaluates proficiency in statistical hypothesis testing, p-value interpretation, and implementing distribution-based calculations (Z and Student-t) in code, and it falls under the Coding & Algorithms domain for data scientist roles.
Scenario
You need a utility that calculates p-values for one-sided and two-sided statistical tests.
Question
Write a Python function compute_p_value(stat, dist='z', df=None, alternative='two-sided') that returns the p-value. Your code should support Z-tests and Student-t tests, and handle 'less', 'greater', and 'two-sided' alternatives.
Hints
Use the CDF of the chosen distribution; for two-sided tests return 2*min(CDF, 1-CDF). Libraries like scipy.stats are allowed.
Compute P-Values for Z and t Tests
Implement compute_p_value(stat, dist='z', df=None, alternative='two-sided') that returns the p-value for one-sided and two-sided tests. For dist='z', use the standard normal distribution. For dist='t', use the Student's t distribution with degrees of freedom df (a positive integer). The alternative can be 'less', 'greater', or 'two-sided'. Compute p-values using the CDF of the chosen distribution: for 'less' return CDF(stat); for 'greater' return 1 - CDF(stat); for 'two-sided' return 2 * min(CDF(stat), 1 - CDF(stat)). Do not use external libraries. Return a float in [0, 1].
Constraints
- dist is 'z' or 't'
- alternative is 'less', 'greater', or 'two-sided'
- For dist='t', df is a positive integer (1 <= df <= 10^6)
- stat is a finite float (|stat| <= 1e6)
- Use only the Python standard library
- Return value within absolute error 1e-9 of the true p-value
Examples
Example 1
Input: stat = 1.96, dist = 'z', alternative = 'two-sided'
Output: 0.049996
Explanation: For a Z-test, CDF(1.96) ≈ 0.9750. Two-sided p-value = 2*min(0.9750, 0.0250) ≈ 0.05.
Example 2
Input: stat = 1.0, dist = 't', df = 1, alternative = 'less'
Output: 0.75
Explanation: For t with df=1 (Cauchy), CDF(1) = 0.5 + arctan(1)/pi = 0.75. One-sided 'less' returns 0.75.
Hints
- For the normal CDF, use erf: Phi(z) = 0.5 * (1 + erf(z / sqrt(2))).
- For the t-distribution CDF, use the regularized incomplete beta function: if t >= 0, F(t) = 1 - 0.5 * I_{nu/(nu + t^2)}(nu/2, 1/2); else F(t) = 0.5 * I_{nu/(nu + t^2)}(nu/2, 1/2).
- Compute the regularized incomplete beta via a continued fraction (Lentz's method).
- For two-sided tests, use 2 * min(CDF, 1 - CDF) and clamp results to [0,1].
Approach
Compute the cumulative distribution function (CDF) of the specified distribution at the test statistic. For the normal distribution, use the error function. For the t-distribution with df degrees of freedom, use the regularized incomplete beta function via a stable continued fraction (Lentz's method). The one-sided p-values are directly CDF or its complement, and the two-sided p-value is 2 * min(CDF, 1 - CDF).
- Time complexity: O(1)
- Space complexity: O(1)