English 中文(简体)
SymPy - Integration
  • 时间:2024-12-22

SymPy - Integration


Previous Page Next Page  

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_pmit, upper_pmit)

>>> 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 −

$frac{x^3}{3} + frac{x^2}{2} + x$


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

The above code snippet gives an output equivalent to the below expression −

$-frac{log(sin(x) - 1)}{2} + frac{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 −

$frac{sqrtpi}{2}$

You can pass multiple pmit 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 −

$frac{pi}{4}$

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


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

The above code snippet gives an output equivalent to the below expression −

$int mathrmlog(x)^2 mathrm{d}x$


>>> 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 −

$sqrtpi * e^{pi^2k^2}$

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)
Advertisements