SciPy Special Functions
Beyond sin, exp and log there is a whole zoo of mathematical functions that keep appearing in physics, statistics and engineering: the gamma function, the error function, Bessel functions, Legendre polynomials and many more. They're called special functions, and scipy.special implements hundreds of them as fast NumPy ufuncs — they work element-wise on whole arrays.
Gamma and factorials
The gamma function Γ(x) extends the factorial to non-integers: Γ(n) = (n − 1)! for whole numbers. It appears in probability distributions everywhere:
import numpy as np
from scipy import special
print("gamma(5) =", special.gamma(5)) # 4! = 24
print("gamma(0.5) =", round(special.gamma(0.5), 6), " sqrt(pi) =", round(np.sqrt(np.pi), 6))
print("factorial(10)=", special.factorial(10, exact=True))
print("comb(52, 5) =", special.comb(52, 5, exact=True), "poker hands")
print("perm(10, 3) =", special.perm(10, 3, exact=True))gamma(5) = 24.0
gamma(0.5) = 1.772454 sqrt(pi) = 1.772454
factorial(10)= 3628800
comb(52, 5) = 2598960 poker hands
perm(10, 3) = 720
Working in log space
Factorials explode quickly: 200! has 375 digits and overflows a float. When you only need ratios or probabilities, compute logarithms instead with gammaln:
import numpy as np
from scipy import special
print("gamma(200):", special.gamma(200)) # overflows to inf
log_f = special.gammaln(201) # log(200!)
print(f"log(200!) = {log_f:.4f} -> about 10^{log_f / np.log(10):.1f}")
# Probability of exactly 100 heads in 200 fair coin flips
n, k = 200, 100
log_p = special.gammaln(n + 1) - special.gammaln(k + 1) - special.gammaln(n - k + 1) - n * np.log(2)
print(f"P(100 heads) = {np.exp(log_p):.5f}")gamma(200): inf
log(200!) = 863.2320 -> about 10^374.9
P(100 heads) = 0.05635
The error function
The error function erf is the integral of the bell curve. It connects directly to the normal distribution: the probability that a normal value lies within k standard deviations of the mean is erf(k / √2):
import numpy as np
from scipy import special
for k in [1, 2, 3]:
print(f"within {k} sigma: {special.erf(k / np.sqrt(2)):.4%}")
print("erfc(3) =", f"{special.erfc(3):.3e}", "(1 - erf, accurate for tiny tails)")
print("erfinv(0.5) =", round(special.erfinv(0.5), 6))within 1 sigma: 68.2689%
within 2 sigma: 95.4500%
within 3 sigma: 99.7300%
erfc(3) = 2.209e-05 (1 - erf, accurate for tiny tails)
erfinv(0.5) = 0.476936
These are the familiar 68–95–99.7 rule numbers.
Bessel functions
Bessel functions describe waves in circular or cylindrical shapes: a vibrating drumhead, heat in a pipe, signals in a coaxial cable. jv(n, x) is the Bessel function of the first kind; jn_zeros(n, k) gives its first k roots, which set a drum's vibration frequencies:
import numpy as np
import matplotlib.pyplot as plt
from scipy import special
x = np.linspace(0, 20, 400)
for n in range(3):
plt.plot(x, special.jv(n, x), label=f"J{n}(x)")
plt.axhline(0, color="gray", lw=0.5)
plt.legend()
plt.title("Bessel functions of the first kind")
plt.show()
zeros = special.jn_zeros(0, 4)
print("first zeros of J0:", np.round(zeros, 4))
print("drum overtone ratios:", np.round(zeros / zeros[0], 3))first zeros of J0: [ 2.4048 5.5201 8.6537 11.7915]
drum overtone ratios: [1. 2.295 3.598 4.903]
The overtones of a drum are not whole-number multiples of the fundamental (unlike a guitar string), which is why drums sound less "musical" than strings.
Orthogonal polynomials
Families of polynomials such as Legendre, Chebyshev, Hermite and Laguerre are used in approximation, quantum mechanics and numerical integration. scipy.special evaluates them and also provides their roots and weights for Gaussian quadrature:
import numpy as np
from scipy import special
x = np.array([-1, -0.5, 0, 0.5, 1])
print("Legendre P2 :", special.eval_legendre(2, x))
print("Chebyshev T3:", special.eval_chebyt(3, x) + 0.0)
# Gauss-Legendre quadrature with 3 points integrates x^4 on [-1, 1] exactly (= 0.4)
nodes, weights = special.roots_legendre(3)
print("nodes :", np.round(nodes, 6))
print("weights:", np.round(weights, 6))
print("integral of x^4:", round(np.sum(weights * nodes ** 4), 10))Legendre P2 : [ 1. -0.125 -0.5 -0.125 1. ]
Chebyshev T3: [-1. 1. 0. -1. 1.]
nodes : [-0.774597 0. 0.774597]
weights: [0.555556 0.888889 0.555556]
integral of x^4: 0.4
Handy everyday functions
scipy.special also contains small utilities that are numerically safer than writing the formula yourself:
| Function | Computes | Why it's better |
|---|---|---|
expit(x) |
logistic 1 / (1 + e⁻ˣ) | no overflow for large negative x |
logit(p) |
log(p / (1 − p)) | inverse of expit |
logsumexp(a) |
log(Σ eᵃ) | avoids overflow in softmax / likelihoods |
softmax(a) |
eᵃ / Σ eᵃ | stable normalisation |
xlogy(x, y) |
x · log(y), with 0 · log 0 = 0 | entropy calculations |
cbrt(x), exp10(x), round(x) |
small helpers | element-wise ufuncs |
import numpy as np
from scipy import special
scores = np.array([1000.0, 1001.0, 1002.0])
with np.errstate(over="ignore", invalid="ignore"): # silence the overflow warnings
print("naive softmax :", np.exp(scores) / np.exp(scores).sum())
print("special.softmax:", np.round(special.softmax(scores), 4))
print("logsumexp :", round(special.logsumexp(scores), 4))
print("expit(-800) :", special.expit(-800.0))
p = np.array([0.5, 0.25, 0.25, 0.0])
print("entropy (bits):", -np.sum(special.xlogy(p, p)) / np.log(2))naive softmax : [nan nan nan]
special.softmax: [0.09 0.2447 0.6652]
logsumexp : 1002.4076
expit(-800) : 0.0
entropy (bits): 1.5
The naive softmax overflows (e^1000 is infinite) and returns nan, while the SciPy version shifts the values internally and gets the right answer.
Test yourself
What is special.gamma(6)?
- 6
- 36
- 120
- 720
Why use gammaln instead of gamma for large arguments?
- It is more precise for small numbers
- gamma overflows to inf, while the logarithm stays finite
- gammaln returns integers
- gamma is deprecated
Which function gives the share of a normal distribution within k standard deviations of the mean?
- special.gamma(k)
- special.erf(k / sqrt(2))
- special.jv(0, k)
- special.expit(k)