SciPy - integrate.newton_cotes() Method



The SciPy integrate.newton-cotes() method is used to return the weights and error coefficient for Newton-Cotes integration. Let's understand the terminology of weight and error coefficient in detail manner −

  • weight: This coefficient applies to the function to represent the specified point. Thus, this operates the integral.
  • error coefficient: The weight is calculated using such a formula which exact integrate the polynoial of certain degree.

Syntax

Following is the syntax of the SciPy integrate.newton-cotes() method −

newton_cotes(int_val)

Parameters

This method accepts only a single parameter by determing the order value in integer form.

Return value

This method returns the result in two different forms − float and list.

Example 1

Following is the basic example that shows the usage of SciPy integrate.newton-cotes() method.

import numpy as np
from scipy import integrate
def exp_fun(x):
    return np.exp(-x)

res = integrate.romberg(exp_fun, 0, 1)
print("The result of integrating exp(-x) from 0 to 1:", res)

# Order of Newton-Cotes rule
rn = 4

# Compute weights and error coefficient
weights, error_coeff = integrate.newton_cotes(rn)
print("The weights is ", weights)
print("The error coefficient is ", error_coeff)

Output

The above code produces the following output −

The result of integrating exp(-x) from 0 to 1: 0.63212055882857
The weights is  [0.31111111 1.42222222 0.53333333 1.42222222 0.31111111]
The error coefficient is  -0.008465608465608466

Example 2

Below the program perform the task on numerical integration using weight.

import numpy as np
from scipy.integrate import newton_cotes

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

# define the interval [a, b]
a = 0
b = np.pi

# Order of Newton-Cotes rule
rn = 3

# calculate weights and error coefficient
weights, _ = newton_cotes(rn)

# calculate the points at which the function is evaluated
x = np.linspace(a, b, rn+1)

# calculate the integral approximation
integral_approx = (b - a) * np.dot(weights, fun(x)) / rn
print("The result of approximate integral:", integral_approx)

Output

The above code produces the following output −

The result of approximate integral: 2.040524284763495
scipy_reference.htm
Advertisements