NumPy Error Function (erf) - How to Use It
Answer
NumPy doesn't have a built-in error function. Use scipy.special.erf() for the error function, or math.erf() for scalar values. The error function is commonly used in statistics for normal distribution calculations and probability.
Why This Happens
The error function (erf) is essential for statistics, probability, signal processing, and physics. It's the integral of the Gaussian distribution. Many people expect it in NumPy, but it lives in SciPy's special functions module.
Solution
The rule: for the error function, use scipy.special.erf(). For normal distribution probabilities, scipy.stats.norm.cdf() is more direct.
import numpy as np
from scipy import special
import math
# โ
Using scipy.special.erf (works with arrays)
x = np.array([-2, -1, 0, 1, 2])
result = special.erf(x)
# Result: [-0.995, -0.843, 0.0, 0.843, 0.995]
# โ
For single values, math.erf works too
result = math.erf(1.0) # 0.8427...
# โ
Complementary error function (1 - erf)
result = special.erfc(x)
# โ
Inverse error function
result = special.erfinv(0.5) # returns x where erf(x) = 0.5
# โ
Common use: convert to normal distribution probabilities
# P(X < x) for standard normal = 0.5 * (1 + erf(x / sqrt(2)))
def normal_cdf(x):
return 0.5 * (1 + special.erf(x / np.sqrt(2)))
probabilities = normal_cdf(np.array([-1, 0, 1, 2]))
# Result: [0.159, 0.5, 0.841, 0.977]
# โ
Alternative: use scipy.stats directly for normal distribution
from scipy import stats
probabilities = stats.norm.cdf([-1, 0, 1, 2])
# โ
If you can't install scipy, approximate erf
def approx_erf(x):
# Abramowitz and Stegun approximation
a1, a2, a3, a4, a5 = 0.254829592, -0.284496736, 1.421413741, -1.453152027, 1.061405429
p = 0.3275911
sign = np.sign(x)
x = np.abs(x)
t = 1.0 / (1.0 + p * x)
y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t * np.exp(-x*x)
return sign * yBetter Workflow
Zerve comes with SciPy pre-installed, so you can use special.erf() immediately. No environment setup, no dependency management, no compatibility issues. Go from idea to implementation in seconds. Visualizations render instantly as block outputs, so you can see your erf curves and probability distributions immediately. Explore multiple parameter sets in parallel blocks instead of running calculations sequentially.
)
&w=1200&q=75)
&w=1200&q=75)
&w=1200&q=75)