← back

Chi-square Probability Distribution

#176 · Probability · Medium

⊣ Solve on deep-ml.com

Problem

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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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)

Explanation

  1. PDF: The chi-square PDF is f(x; k) = x^(k/2-1) * e^(-x/2) / (2^(k/2) * Gamma(k/2)) for x > 0.
  2. CDF: Computed using the regularized lower incomplete gamma function via series expansion: P(k/2, x/2) = sum of (x/2)^(k/2+i) * e^(-x/2) / Gamma(k/2+i+1).
  3. The series converges quickly for moderate values of x.
  4. The chi-square distribution with k degrees of freedom is the sum of k independent standard normal squared random variables.

Complexity

  • Time: O(n_terms) for CDF series, O(1) for PDF
  • Space: O(1)