Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easily available implementation of erf() for Python?

Tags:

python

math

I can implement the error function, erf, myself, but I'd prefer not to. Is there a python package with no external dependencies that contains an implementation of this function? I have found this but this seems to be part of some much larger package (and it's not even clear which one!).

like image 885
rog Avatar asked Jan 19 '09 12:01

rog


People also ask

How does Python calculate erf?

The math. erf() method returns the error function of a number. This method accepts a value between - inf and + inf, and returns a value between - 1 to + 1.

What is the difference between erf and erfc?

The error function, generally denoted by erf is defined as. Sometimes it is called the probability integral [1], in which case, erf denotes the integral itself without the normalization factor . The complementary error function denoted by erfc is defined as erfc = 1 − erf .


2 Answers

Since v.2.7. the standard math module contains erf function. This should be the easiest way.

http://docs.python.org/2/library/math.html#math.erf

like image 63
golobor Avatar answered Sep 24 '22 10:09

golobor


I recommend SciPy for numerical functions in Python, but if you want something with no dependencies, here is a function with an error error is less than 1.5 * 10-7 for all inputs.

def erf(x):     # save the sign of x     sign = 1 if x >= 0 else -1     x = abs(x)      # constants     a1 =  0.254829592     a2 = -0.284496736     a3 =  1.421413741     a4 = -1.453152027     a5 =  1.061405429     p  =  0.3275911      # A&S formula 7.1.26     t = 1.0/(1.0 + p*x)     y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)     return sign*y # erf(-x) = -erf(x) 

The algorithm comes from Handbook of Mathematical Functions, formula 7.1.26.

like image 43
John D. Cook Avatar answered Sep 24 '22 10:09

John D. Cook