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…

--

--

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