Integration with SymPy or Scipy

Shen Ge
3 min readDec 1, 2021
Photo by Jeswin Thomas on Unsplash

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.

Using Sympy

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))
print(expr_int)

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.

Using SciPy

SciPy’s 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,1
def integrand(x, a, b):
return a*x**2 + b
expr_int_scipy = quad(integrand, 0, 1, args=(a,b))
print(expr_int_scipy)

Running this short snippet in ipython outputs the following.

%run integrate_example.py
(1.6666666666666667, 1.8503717077085944e-14)

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.

--

--

Shen Ge

Engineer and console operator who helped America land back on the moon 2/22/2024. Enjoys code + poetry. Become a member: https://medium.com/@shenge86/membership