In this Python and scientific computing tutorial, we will learn how to perform symbolic integration in Python. We will learn how to compute definite and indefinite integrals in Python by using the symbolic Python library called SymPy. The YouTube tutorial accompanying this post is given here.
Indefinite Integrals in Python
First, we explain how to implement this integral
(1)
where
# import all the packages
from sympy import *
# use this function for nice priting of symbolic expressions
init_printing()
# first test, let us integrate y=x^2 function
x=Symbol('x')
function1=x**2
y=integrate(function1,x)
First, we import all functions and objects from the SymPy library. We call the function init_printing() to nicely print symbolic expressions. We define the symbolic variable x, by using “x=Symbol(‘x’)”. Then, we define our quadratic function, which we call function1. Finally, we integrate the function by using SymPy function “integrate”. The first argument of this function is the function that we want to integrate, and the second argument is the variable that is used for integration. The function “integrate()” returns the function that is obtained after integration.
We can double-check this result by differentiating the function
# let us double check, by differentiating the function y
function2=diff(y,x)
function2-function1
We use the SymPy function “diff()” to perform differentiation. The first argument of this function is the function, and the second input argument is the variable that is used for differentiation.
Next, let us solve a more complex integral. We solve the following integral that is usually analytically solved by using the substitution:
(2)
where
function2=x/sqrt(1-4*x**2)
y2=integrate(function2,x)
function3=diff(y2,x)
function3-function2
Here, we also double-checked the results by differentiating the integrated function.
Next, we solve the following integral
(3)
# let us now try to solve tan(x) integral
function4=tan(x)
y3=integrate(function4,x)
# capital E is the e number...
log(E)
# log is actually ln
function5=diff(y3,x)
simplify(function5-function4)
Here, we have to make a few important comments. The integrate function will return
Definite Integrals in Python
Let us first learn how to integrate a constant
(4)
# import all the packages
from sympy import *
# use this function for nice priting of symbolic expressions
init_printing()
# first test, let us integrate y=x^2 function
x=Symbol('x')
# compute definite integral
a=1
b=3
integrate(1 ,(x, a, b))
We use the function “integrate()”. The first argument is the function that needs to be integrated and the second argument is the tuple. The first entry of the tuple is the symbolic variable that is used for integration,
Next, let us compute this integral
(5)
# let us now try this
integrate(cos(x),(x,0,2*pi))
Next, let us solve this integral
(6)
We solve this integral by using the following script:
# let us try this
integrate(x,(x,0,3))