In this Python tutorial, we will learn about the “Scipy Integrate” where we will learn about how to use the integration method to solve integration problems. And additionally, we will cover the following topics.
- Scipy Integrate
- Scipy Integrate Simpson
- Scipy Integrate Trapzoid
- Scipy Integrate Quad
- Scipy Integrate Odeint
- Scipy Integrate Solve_Ivp
- Scipy Integrate CumTrapz
Scipy Integrate
The Scipy submodule scipy.integrate
contains the many methods to solve problems related to integrations or differential equations in Python. It has a predefined function and method to solve the integration or differential equation mathematics problems.
To know the available integration techniques within this submodule, use the below code.
from scipy import integrate
print(help(integrate))
In the above output, when we will scroll through, then it shows all the integration or differential techniques, methods, and functions in this module.
Read: Scipy Stats – Complete Guide
Scipy Integrate Trapzoid
The TrapeZoid
rule is an integration technique that evaluates the area under the curve by dividing the total area into a smaller trapezoid. It integrates a given function y(x)
based on a specified axis.
The syntax for using it in Python is given below.
scipy.integrate.trapezoid(y, x=None, dx=1.0, axis=- 1)
Where parameters are:
- y(array_data): It represents the array that we want to integrate as input.
- x(array_data): It is used to specify the sample points that relate to y values.
- dx(scalar): It is used to specify the space between sample points when the
x
isn’t used. - axis(int): It defines the on which axis we want to perform the integration.
The method trapezoid()
returns the value trapz
of type float which is approximated integral value.
Let’s take an example by following the below steps in Python:
Import the required libraries.
from scipy.integrate import trapezoid
Create array values that represent the y
data and pass it to the method.
trapezoid([5,8,10])
The output shows the integration value 15.5
by applying the trapezoid rule.
Read: Scipy Misc + Examples
Scipy Integrate Simpson
The Scipy has a method simpson()
that calculates the approximate value of an integral. This method exists in the submodule scipy.integrate
.
The syntax for using it in Python is given below.
scipy.integrate.simpson(y, x=None, dx=1.0, axis=- 1, even='avg')
Where parameters are:
- y(array_data): It represents the array that we want to integrate as input.
- x(array_data): It is used to specify the sample points that relate to y values.
- dx(scalar): It is used to specify the space between sample points when the
x
isn’t used. - axis(int): It defines the on which axis we want to perform the integration.
- even(string): It is used to specify the trapezoidal rule on the average of two results, the first and the last interval.
Let’s take an example using the below steps:
Import the required module as shown below code.
import numpy as np
from scipy.integrate import simpson
Create an array of data and sample points using the below code.
array_data = np.arange(5,15)
sample_pnt = np.arange(5,15)
Use the below Python code to calculate the integration using the method simpson()
.
simpson(array_data,sample_pnt)
The output shows the integral value of the array and the given sample points are 85.5.
Read: Scipy Rotate Image + Examples
Scipy Integrate Quad
The Scipy has a method quad()
in the submodule scipy.integrate
that calculate the definite integral of a given function from infinite interval a to b in Python.
The syntax is given below.
scipy.integrate.quad(func, a, b, args=(), full_output=0)
Where parameters are:
- func(function): It is used to specify the function that is used for the computation of integration. The function can be one of the following forms.
- double func(double y)
- double func(double y, void *user_data)
- double func(int m, double *yy)
- double func(int m, double *yy, void *user_data)
- a(float): Used to specify the lower limit of integration.
- b(float): Used to specify the upper limit of integration.
- args(tuple): If we want to pass extra arguments to a function, then use this parameter.
- full_output(int): Non-zero value is used to get the dictionary of integration information.
The method returns three important results y
the integral value, abserr
the estimate of the absolute error, and infodict
the dictionary containing additional information.
Let’s take an example by following the below steps:
Import the required library using the below Python code.
from scipy.integrate import quad
Create a function using the lambda function and define the interval as shown in the below code.
n3 = lambda n: n**3
a = 0
b = 5
Now calculate the integration of the function using the below code.
quad(n3, a, b)
The output shows the definite integral value of the function n3 (n to the power 3) is 156.25000
.
Read: Scipy Sparse – Helpful Tutorial
Scipy Integrate Odeint
The Scipy submodule scipy.integrate
contains method odeint()
that integrate ordinary differential equations.
The syntax for using it in Python is given below.
scipy.integrate.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, printmessg=0)
Where parameters are:
- func: It computes the derivative of function y at t.
- y0(array): It is used to provide the initial condition for y.
- t(array): It is a series of time point
- args: It is used to provide the extra arguments to a function y.
- Dfun: Used for the gradient of a function.
- col_deriv(boolean): For true values
Dfun
define the derivate down to columns, otherwise across to rows in case of false. - printmessg(boolean): Used for printing the convergence message.
The function contains many parameters but here above we have explained only common parameters.
The method odient()
returns two values y
that are array containing the value of y for each time t and the infodict
for additional output information.
Let’s take an example by following the below steps:
Import the required libraries.
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np
Define the equation using the below code.
def diff_model(y,t):
k = 0.5
dydt = -k * y
return dydt
Create an initial condition using the below code.
y0 = 3
Create a series of time points using the below code.
t = np.linspace(0,15)
Solve the created equation by providing the parameters using the below code.
y = odeint(diff_model,y0,t)
Now plot the solution using the below code.
plt.plot(t,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()
This is how to integrate ordinary differential equations.
Read: Scipy Constants
Scipy Integrate Solve_Ivp
The Scipy has a method solve_ivp()
that integrates a system of ordinary differential equations based on the provided initial value.
The syntax for using it in Python is given below.
scipy.integrate.solve_ivp(fun, t_span, y0, method='BDF', t_eval=None, dense_output=False, events=None, vectorized=True, args=None)
Where parameters are:
- fun(callable): It is on the right-hand side of the system. The signature of the calling function is fun(x,z) where x represents scalar and z is a ndarray that represent the shape in two way.
- t_span(two tuple floats): It represents the interval of integration from t0 to t1.
- y0(array_data like shape(n)): Used for specifying the initial state.
- method(string or odsolver): It is used to specify which integration method to use like RK45, Radau, RK23, DOP853, BDF, and LSODA.
- t_eval(array_data): It is used to specify the times at which to store the calculated solution.
- dense_output(boolean): It is used to specify whether we want to calculate the continuous solution or not.
- events(callable): It is used for tracking events.
- Vectorized(boolean): It is used to specify whether we want to implement the function in a vectorized way or not.
- args(tuple): To pass extra arguments.
The function returns the bunch object containing many values but it has two important values that are y and t.
Let’s take an example by following the below steps:
Import the required libraries using the below python code.
from scipy.integrate import solve_ivp
Create an exponential decay function using the below code.
def exp_decay(t, y): return -1.0 * y
Now apply the method solve_ivp()
on exponential decay function using the below code.
solution = solve_ivp(exp_decay, [5, 15], [4, 6, 10])
Check the t
value that is stored within the solution.
solution.t
Check the y
value that is stored within the solution.
solution.y
This is how to integrate a system of ordinary differential equations based on the provided initial value.
Read: Scipy Optimize – Helpful Guide
Scipy Integrate CumTrapz
The cumtrapez
the rule is an integration technique that cumulatively integrates the given function y(x) with the help of the trapezoid rule.
The syntax is given below.
scipy.integrate.cumtrapz(y, x=None, dx=1.0, axis=- 1, intial=None)
Where parameters are:
- y(array_data): It represents the array that we want to integrate as input.
- x(array_data): It is used to specify the sample points that relate to y values.
- dx(scalar): It is used to specify the space between sample points when the
x
isn’t used. - axis(int): It defines the on which axis we want to perform the integration.
- initial(scalar): It is used to provide the initial value to function.
The method trapezoid()
returns the value res
of type ndarray.
Let’s take an example by following the below steps:
Import the required libraries using the below python code.
from scipy.integrate import cumtrapz
import numpy as np
Create variable sample_pts which are sample points and y3 which is for integration using the below code.
sample_pts = np.arange(5, 30)
y_func = np.power(sample_pts, 3)
Use the method cumtrapz()
on function using the below code.
cumtrapz(y_func,sample_pts)
This is how to use the method cumtrapz()
to integrate the given function.
Also, take a look at some more SciPy tutorials.
- Python Scipy Special
- Scipy Signal – Helpful Tutorial
- Scipy Ndimage Rotate
- Python Scipy Stats Kurtosis
- Python Scipy Chi-Square Test
- Python Scipy Stats Multivariate_Normal
- Scipy Normal Distribution
In this tutorial, we have learned about the “Scipy Integrate” and we have also covered the following topics.
- Scipy Integrate
- Scipy Integrate Simpson
- Scipy Integrate Trapzoid
- Scipy Integrate Quad
- Scipy Integrate Odeint
- Scipy Integrate Solve_Ivp
- Scipy Integrate CumTrapz
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.