SciPy - integrate.quad() Method



The SciPy integrate.quad() method is used to perform the task of definite integrals. It is commonly known as quadtrate(set of two points).

Syntax

Following is the syntax of the SciPy integrate.quad() method −

quad(custom_func, upper_lim, lower_lim)

Parameters

This method accepts the following parameter −

  • custom_func: This parameter set the user defined function for integral calculation.
  • upper_lim: This parameter is used to set the upper limit.
  • lower_lim: This parameter is used to set the lower limit.

Return value

This method returns either a numerical integer or absolute error as result.

Example 1

Following is the basic example that illustrate the usage of SciPy integrate.quad() method.

from scipy import integrate

# define the function
def fun(x):
    return x**2

# Perform the integration
res, err = integrate.quad(fun, 0, 1)

print("The result is ", res)
print("The estimated error is ", err)

Output

The above code produces the following output −

The result is  0.33333333333333337
The estimated error is  3.700743415417189e-15

Example 2

This program defines the definite integral of a function which is f(x) = sin(x) over the interval from 0 to pi.

import scipy.integrate as sp
import numpy as np

# define the function
def fun(x):
    return np.sin(x)

# perform the integration
res, err = sp.quad(fun, 0, np.pi)

print("The result is ", res)
print("The estimated error is ", err)

Output

The above code produces the following output −

The result is  2.0
The estimated error is  2.220446049250313e-14

Example 3

Here, we illustrate the exponential function(e-x2) within an user-defined function and perform the resultant integration using quad(). Here, range interval is set between -inf and inf.

import scipy.integrate as sp
import numpy as np

# define the function
def fun(x):
    return np.exp(-x**2)

# Perform the integration
res, err = sp.quad(fun, -np.inf, np.inf)

print("The result is ", res)
print("The estimated error is ", err)

Output

The above code produces the following output −

The result is  1.7724538509055159
The estimated error is  1.4202636780944923e-08
scipy_reference.htm
Advertisements