SymPy – Integration

The SymPy package contains integrals module. It implements methods to calculate definite and indefinite integrals of expressions. The integrate() method is used to compute both definite and indefinite integrals. To compute an indefinite or primitive integral, just pass the variable after the expression.

For example βˆ’

integrate(f, x)

To compute a definite integral, pass the argument as follows βˆ’

(integration_variable, lower_limit, upper_limit)
>>> from sympy import * 
>>> x,y = symbols('x y') 
>>> expr=x**2 + x + 1 
>>> integrate(expr, x)

The above code snippet gives an output equivalent to the below expression βˆ’

x3/3+x2/2+x

>>> expr=sin(x)*tan(x) 
>>> expr 
>>> integrate(expr,x)

The above code snippet gives an output equivalent to the below expression βˆ’

βˆ’(log(sin(x)βˆ’1)/2)+(log(sin(x)+1)/2)βˆ’sin(x)

The example of definite integral is given below βˆ’

>>> expr=exp(-x**2) 
>>> integrate(expr,(x,0,oo) )

The above code snippet gives an output equivalent to the below expression βˆ’

√ Ο€/ 2

You can pass multiple limit tuples to perform a multiple integral. An example is given below βˆ’

>>> expr=exp(-x**2 - y**2)
>>> integrate(expr,(x,0,oo),(y,0,oo))

The above code snippet gives an output equivalent to the below expression βˆ’

Ο€/4

You can create unevaluated integral using Integral object, which can be evaluated by calling doit() method.

>>> expr = Integral(log(x)**2, x) 
>>> expr

The above code snippet gives an output equivalent to the below expression βˆ’

∫log(x)2dx

>>> expr.doit()

The above code snippet gives an output equivalent to the below expression βˆ’

xlog(x)2βˆ’2xlog(x)+2x

Integral Transforms

SymPy supports various types of integral transforms as follows βˆ’

  • laplace_transform
  • fourier_transform
  • sine_transform
  • cosine_transform
  • hankel_transform

These functions are defined in sympy.integrals.transforms module. Following examples compute Fourier transform and Laplace transform respectively.

Example 1

>>> from sympy import fourier_transform, exp 
>>> from sympy.abc import x, k 
>>> expr=exp(-x**2) 
>>> fourier_transform(expr, x, k)

On executing the above command in python shell, following output will be generated βˆ’

sqrt(pi)*exp(-pi**2*k**2)

Which is equivalent to βˆ’

βˆšβˆ—eΟ€2k2

Example 2

>>> from sympy.integrals import laplace_transform 
>>> from sympy.abc import t, s, a 
>>> laplace_transform(t**a, t, s)

On executing the above command in python shell, following output will be generated βˆ’

(s**(-a)*gamma(a + 1)/s, 0, re(a) > -1)

Leave a Reply