Implement the Chi-square probability distribution. Compute the probability density function (PDF) and cumulative distribution function (CDF) for a chi-square distribution with k degrees of freedom.
import math
def chi_square_pdf(x: float, k: int) -> float:
if x < 0:
return 0.0
if x == 0:
if k == 1:
return float('inf')
elif k == 2:
return 0.5
else:
return 0.0
half_k = k / 2.0
coeff = 1.0 / (2 ** half_k * math.gamma(half_k))
return coeff * (x ** (half_k - 1)) * math.exp(-x / 2)
def chi_square_cdf(x: float, k: int, n_terms: int = 200) -> float:
if x <= 0:
return 0.0
half_k = k / 2.0
s = half_k
total = 0.0
term = 1.0 / half_k
value = x / 2.0
total = term
for i in range(1, n_terms):
term *= value / (half_k + i)
total += term
if abs(term) < 1e-15:
break
return total * (value ** half_k) * math.exp(-value) / math.gamma(half_k)f(x; k) = x^(k/2-1) * e^(-x/2) / (2^(k/2) * Gamma(k/2)) for x > 0.P(k/2, x/2) = sum of (x/2)^(k/2+i) * e^(-x/2) / Gamma(k/2+i+1).