Part 5-1
Part 5-1
and
Integration
Using SymPy
f4= sp.cos(3*x**2)
Diff4= sp.diff(f4,x)
print(f4,"ans",Diff4)
- To add value to any variables, use function.subs({variables:value})
Partial Derivative as above : solve the following in x, y ,xy yx (𝑥 4 + 𝑥𝑦 4 )
import sympy as sp
x,y,z=sp.symbols('x y z')
f5= x**4 + x * y**4
pd1=f5.diff(x)
pd2=f5.diff(y)
pd3=f5.diff(x,y)
pd4= f5.diff(y,x)
print(pd1)
print(pd2)
print(pd3)
print(pd4)
Integration: The SymPy module in Integration consists of integral modules. The syntax for
calculating Integration in python is as followed: sp.integrate(function, variable)
Example: integrate (𝑦4 + 𝑦 + 2)
import sympy as sp
x,y,z=sp.symbols('x y z')
f6= y**4+ y+ 2
ing1= sp.integrate(f6,y)
#or
ing1= f6.integrate(x)
print(ing1)
- To add value to any variables, use function.subs({variables:value})
h=pd1.subs({x:1})
print(h)
more visit SymPy 1.11 documentation
Using scipy
When a function cannot be integrated analytically, or is very difficult generally turns to numerical
integration methods. SciPy has a number of routines for performing numerical integration that can be
found in scipy.integrate library. Below you can find some
Function Description
quad single integration
dblquad double integration
tplquad triple integration
nquad n-fold multiple integration
fixed_quad Gaussian quadrature, order n
quadrature Gaussian quadrature to tolerance
romberg Romberg integration
polyint Analytical polynomial integration (NumPy)
poly1d Helper function for polyint (NumPy)
Single integrals:
The function quad is the workhorse of SciPy’s integration functions. The general form of quad is
scipy.integrate.quad(f, a, b), where f is the
name of the function to be integrated and a and b are the lower and upper limits, respectively.
1 −2
Example:∫0 𝑒 𝑥
import scipy.integrate
f = lambda x : exp(-x**2)
scipy.integrate.quad(f, 0, 1)
the output (0.7468241328124271, 8.291413475940725e-15)
lambda expression used as an anonymous function, a function with no name, as promised in the section Anonymous
functions (lambda).
The first is 0.7468..., is the value of the integral, and the second is 8.29...e-15, is an estimate of the absolute error.
The quad function handles infinite limits just fine.( inf or -inf)
Integrating polynomials:
the NumPy poly1d and the NumPy function polyint takes the n th antiderivative of a polynomial and can be used to
evaluate definite integrals.
Example: integrate 2𝑥 2 + 5𝑥 1 + 1
p = np.poly1d([2, 5, 1])
p
Output: poly1d([2, 5, 1])
p(1), p(2), p(3.5)
Output: (8, 19, 43.0)
To find the integral
In [15]: P = polyint(p)
In [16]: P
Output: poly1d([ 0.66666667, 2.5 , 1. , 0. ])
To find the integral from 1 to 5
In [17]: q=P(5)-P(1)
In [18]: q
Output: 146.66666666666666
Double integrals: