← back

Exponential Distribution PDF and CDF

#340 · Statistics · Easy

⊣ Solve on deep-ml.com

Problem

Implement the Exponential distribution PDF and CDF. The exponential distribution models the time between events in a Poisson process, parameterized by rate lambda.

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
import math
from typing import Dict

def exponential_pdf(x: float, lam: float) -> float:
    if lam <= 0:
        raise ValueError("Rate parameter lambda must be positive")
    if x < 0:
        return 0.0
    return lam * math.exp(-lam * x)

def exponential_cdf(x: float, lam: float) -> float:
    if lam <= 0:
        raise ValueError("Rate parameter lambda must be positive")
    if x < 0:
        return 0.0
    return 1.0 - math.exp(-lam * x)

def exponential_statistics(lam: float) -> Dict[str, float]:
    if lam <= 0:
        raise ValueError("Rate parameter lambda must be positive")
    return {
        "mean": round(1.0 / lam, 4),
        "variance": round(1.0 / (lam ** 2), 4),
        "std_dev": round(1.0 / lam, 4),
        "median": round(math.log(2) / lam, 4)
    }

def exponential_quantile(p: float, lam: float) -> float:
    if p < 0 or p > 1:
        raise ValueError("Probability must be in [0, 1]")
    if lam <= 0:
        raise ValueError("Rate parameter lambda must be positive")
    if p == 1:
        return float('inf')
    return -math.log(1 - p) / lam

Explanation

  1. PDF: f(x; lambda) = lambda exp(-lambda x) for x >= 0, zero otherwise.
  2. CDF: F(x; lambda) = 1 - exp(-lambda * x) for x >= 0.
  3. Statistics: Mean = 1/lambda, Variance = 1/lambda^2, Median = ln(2)/lambda.
  4. Quantile (inverse CDF): x = -ln(1 - p) / lambda, useful for sampling via inverse transform.

Complexity

  • Time: O(1) for all operations
  • Space: O(1)