viva_math/special

Special mathematical functions.

Implementations focus on functions that complement gleam_community_maths and are needed by viva_math/distributions for Gamma/Beta/Dirichlet distributions, by viva_math/free_energy for KL divergences of exponential-family distributions, and by viva_math/entropy for the differential entropy of those families.

Algorithms

References

Values

pub fn beta(x: Float, y: Float) -> Float

Beta function B(x, y) = Γ(x)·Γ(y)/Γ(x+y). Always computed via lgamma to avoid overflow.

pub fn binomial(n: Int, k: Int) -> Result(Float, Nil)

Binomial coefficient C(n, k) = n! / (k!·(n-k)!) via lgamma for stability.

pub fn digamma(x: Float) -> Float

Digamma function ψ(x). Defined for x > 0.

Combines the recurrence ψ(x) = ψ(x+1) - 1/x to push x ≥ 20, then evaluates the asymptotic series ψ(x) ≈ ln x - 1/(2x) - Σ B₂ₖ / (2k·x^(2k)).

pub fn factorial(n: Int) -> Result(Float, Nil)

Factorial n! for non-negative integer n.

Exact for n ≤ 20 (fits in i64). For larger n falls back to Γ(n+1) via Lanczos, with attendant ~15-digit relative accuracy.

pub fn gamma(x: Float) -> Float

Gamma function Γ(x). Overflows past x ≈ 171.6 — prefer lgamma.

pub fn lbeta(x: Float, y: Float) -> Float

Logarithm of the beta function — ln B(x, y).

pub fn lgamma(x: Float) -> Float

Logarithm of the gamma function ln Γ(x). Defined for x > 0.

Uses the Lanczos approximation with g=7, accurate to ~15 digits.

Search Document