← back

Beta Distribution PDF and Statistics

#339 · Statistics · Medium

⊣ Solve on deep-ml.com

Problem

Implement the Beta distribution probability density function (PDF) and compute its key statistics (mean, variance, mode). The Beta distribution is defined on [0, 1] with shape parameters alpha and beta.

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
32
33
34
35
36
37
38
39
import math
from typing import Dict

def beta_function(a: float, b: float) -> float:
    return math.gamma(a) * math.gamma(b) / math.gamma(a + b)

def beta_pdf(x: float, alpha: float, beta: float) -> float:
    if x < 0 or x > 1:
        return 0.0
    if alpha <= 0 or beta <= 0:
        raise ValueError("Alpha and beta must be positive")

    if x == 0:
        return float('inf') if alpha < 1 else (1.0 if alpha == 1 else 0.0)
    if x == 1:
        return float('inf') if beta < 1 else (1.0 if beta == 1 else 0.0)

    B = beta_function(alpha, beta)
    return (x ** (alpha - 1) * (1 - x) ** (beta - 1)) / B

def beta_statistics(alpha: float, beta: float) -> Dict[str, float]:
    mean = alpha / (alpha + beta)
    variance = (alpha * beta) / ((alpha + beta) ** 2 * (alpha + beta + 1))

    if alpha > 1 and beta > 1:
        mode = (alpha - 1) / (alpha + beta - 2)
    elif alpha <= 1 and beta <= 1 and alpha != 1 and beta != 1:
        mode = None  # Bimodal at 0 and 1
    elif alpha <= 1:
        mode = 0.0
    else:
        mode = 1.0

    return {
        "mean": round(mean, 4),
        "variance": round(variance, 6),
        "mode": round(mode, 4) if mode is not None else None,
        "std_dev": round(variance ** 0.5, 4)
    }

Explanation

  1. The Beta PDF is: f(x; a, b) = x^(a-1) * (1-x)^(b-1) / B(a, b), where B(a, b) is the Beta function.
  2. The Beta function B(a, b) = Gamma(a) * Gamma(b) / Gamma(a + b).
  3. Mean = a / (a + b), Variance = ab / ((a+b)^2 * (a+b+1)).
  4. Mode = (a-1) / (a+b-2) when both a > 1 and b > 1. Boundary cases handle degenerate shapes.

Complexity

  • Time: O(1) for PDF evaluation and statistics
  • Space: O(1)