SciPy - integrate.simpson() Method



The SciPy integrate.simpson() method is used to approximate the integral of a function using simpson rule. This rule is works upon even number of interval.

Suppose, there are two sample N(even number) and N-1(odd number). To handle the situation of odd interval, the simpson() method provides the even parameter to control this.

Syntax

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

simpson(y, x)

Parameters

This method accepts two parameter −

  • y: This parameter represent the simple mathematical tasks such as sin(), exp(), etc.
  • x: By using this parameter, we can represent the following − array and built-in function.

Return value

This method returns the float value as result.

Example 1

Following is the basic example that shows the usage of SciPy integrate.simpson() method.

import numpy as np
from scipy import integrate

# 100 sample points between 0 and 10
x = np.linspace(0, 10, 100)  
y = x**2

res_integral = integrate.simpson(y, x)
print("The resultant value is ", res_integral)

Output

The above code produces the following result −

The resultant value is  333.333505101692

Example 2

Here, we integrate the sin(x) function from the range of 0 to pi using Simpson rule with 50 sample points.

import numpy as np
from scipy.integrate import simpson

# 50 sample points between 0 and 
x = np.linspace(0, np.pi, 50)  
y = np.sin(x)

res_integral = simpson(y, x)
print("The resultant value is ", res_integral)

Output

The above code produces the following result −

The resultant value is  1.999999483788026

Explanation: This is an approximate value which is very close 2 and it determines the high accuracy when handling the odd intervals.

Example 3

Below is the another program using simpson rule which shows the given input as an array of list(x). Then it use the exp() which helps to set the small number of data points(even). Finally, the result(approximate value) obtained using simpson method.

import numpy as np
from scipy.integrate import simpson

x = np.array([0, 0.1, 0.4, 0.8, 1.0])
y = np.exp(x)

res_integral = simpson(y, x)
print("The resultant value is ", res_integral)

Output

The above code produces the following result −

The resultant value is  1.7173084152992835
scipy_reference.htm
Advertisements