Python Error Function Erf
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business python inverse error function Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation python erfc Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like pi in python you, helping each other. Join them; it only takes a minute: Sign up Is there an easily available implementation of erf() for Python? up vote 36 down vote favorite 7 I can implement the error function, erf, python import math 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 http://pylab.sourceforge.net/packages/included_functions.html>this but this seems to be part of some much larger package (and it's not even clear which one!). I'm sorry if this is a naive question - I'm totally new to Python. python math share|improve this question asked Jan 19 '09 at 12:10 rog 2,21211721 add a comment| 7 Answers
Math Domain Error
7 active oldest votes up vote 44 down vote 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 share|improve this answer edited Nov 19 '13 at 14:28 Colonel Panic 53.3k33221278 answered Jul 12 '11 at 9:31 bezalel 59146 1 +1: simplest answer. –Neil G Dec 21 '11 at 4:42 Wow! Never noticed that! –smci May 20 '13 at 23:30 Is there a Python module that provides erf⁻¹(x) ? –Lori Feb 1 '15 at 22:49 add a comment| up vote 39 down vote 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. share|improve this answer edited Dec 21 '11 at 4:41 Neil G 11.1k1982168 answered Jan 19 '09 at 14:46 J
19 January 2009 by John The question came up on StackOverflow this morning how to compute the error function erf(x) in Python. The standard answer for how to compute anything numerical in Python is "Look in SciPy." However, this person didn't want to take on the dependence on SciPy. I've
Python Math Operators
seen variations on this question come up in several different contexts lately, including module 'scipy' has no attribute 'special' questions about computing the normal distribution function, so I thought I'd write up a solution.Here's a Python implementation of erf(x) based python float to int on formula 7.1.26 from A&S. The maximum error is below 1.5 × 10-7.import math def erf(x): # constants a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 http://stackoverflow.com/questions/457408/is-there-an-easily-available-implementation-of-erf-for-python p = 0.3275911 # Save the sign of x sign = 1 if x < 0: sign = -1 x = abs(x) # A & S 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*yThis problem is typical in two ways: A&S has a solution, and you've got to know a little background before you can http://www.johndcook.com/blog/2009/01/19/stand-alone-error-function-erf/ use it.The formula given in A&S is only good for x ≥ 0. That's no problem if you know that the error function is an odd function, i.e. erf(-x) = -erf(x). But if you're an engineer who has never heard of the error function but needs to use it, it may take a while to figure out how to handle negative inputs.One other thing that someone just picking up A&S might not know is the best way to evaluate polynomials. The formula appears as 1 - (a1t1 + a2t2 + a3t3 + a4t4 + a5t5)exp(-x2), which is absolutely correct. But directly evaluating an nth order polynomial takes O(n2) operations, while the factorization used in the code above uses O(n) operations. This technique is known as Horner's method. Categories : Computing Math PythonTags : Python Special functionsBookmark the permalink Post navigationPrevious PostDraw a bigger pictureNext PostStand-alone normal (Gaussian) distribution function 14 thoughts on “Stand-alone error function erf(x)” Sergey Fomel 19 January 2009 at 16:21 erf is actually a standard function in C "math.h"For some reason, it is not included in Python's math module but, if you have SWIG, it is easy to write a SWIG wrapper for it. An example on a Linux
module is always available. It provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the https://docs.python.org/2/library/math.html cmath module if you require support for complex numbers. The distinction http://rajeshrinet.github.io/blog/2014/numpy-matplotlib/ between functions which support complex numbers and those which don't is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so error function that the programmer can determine how and why it was generated in the first place. The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats. 9.2.1. Number-theoretic and representation functions¶ math.ceil(x)¶ Return the ceiling of x as a float, the smallest integer value greater than or equal to x. math.copysign(x, y)¶ Return x with the python error function sign of y. On a platform that supports signed zeros, copysign(1.0, -0.0) returns -1.0. New in version 2.6. math.fabs(x)¶ Return the absolute value of x. math.factorial(x)¶ Return x factorial. Raises ValueError if x is not integral or is negative. New in version 2.6. math.floor(x)¶ Return the floor of x as a float, the largest integer value less than or equal to x. math.fmod(x, y)¶ Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python's x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python's -1e-100 % Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Plotting using matplotlib In[2]: %matplotlib inline import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 4*np.pi, 64) plt.plot(x, np.sin(x), '*-'); We can improve on the above plot in several ways. E.g setting axis labels. setting axis limits. chossing color of our choice. putting legends ... In the plot below we have included some of these features along with another plot in the same figure. This can be used to compare between two plots on the same figure. In[13]: %matplotlib inline import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 4*np.pi, 64) plt.plot(x, np.sin(x), color="#348ABD", linewidth=2, linestyle="-", label='sin(x)'); plt.plot(x, np.cos(x), color="#A60628", linewidth= 3, linestyle="-", label='cos(x)'); plt.xlim([0, 4*np.pi]); plt.xlabel('x'); plt.legend(loc="lower left") Out[13]: