Integration is a critical part of applications requiring the use of calculus. How do we proceed to integrate a function in Python? There are multiple libraries but I will focus on the two most popular ones — symbolic integration with SymPy and numerical integration with SciPy. Both can work but the code is different for either. Which one you decide to use depends on your particular code.
Let us use a simple example. Suppose we want to integrate the polynomial function ax² + b with respect to x from 0 to 1 assuming a=2 and b=1.
Let us use the
integral() module in SymPy to integrate analytically.
from sympy import *
x,y = symbols('x y')
a,b = 2,1
expr = a*x**2 + b
expr_int = integrate(expr,x)
expr_int = integrate(expr,(x,0,1))
I saved this little snippet as
integrate_example.py and I ran it in ipython to acquire the following.
As can be seen I can do both an indefinite integral as well as a definite integral here. The result of the definite integral is given as a fraction 5/3.
integratesubpackage has as a variety of numerical integration methods which you can utilize. Here, we demonstrate the usage of the general purpose integrator
quad()which for those more mathematically inclined is called quadrature. We note that the SciPy subpackage does not allow us to calculate an indefinite integral since it is numerical.
from scipy.integrate import quad
a,b = 2,1def integrand(x, a, b):
return a*x**2 + bexpr_int_scipy = quad(integrand, 0, 1, args=(a,b))
Running this short snippet in ipython outputs the following.
We have a tuple as the output. The first element of the tuple is the estimated value of the integral which is expressed as a decimal. The second element is the upper bound of the error. This means that the numerically computed integral is within O(-14) of the exact result. This is small enough that we can be confident of the approximated value.