How to Perform 2D Integrals in SciPy?

Python SciPy | 2D Integrals: In this tutorial, we will learn how to perform 2D integrals in SciPy using multiple approaches/methods. By Pranit Sharma Last updated : June 07, 2023

2D Integrals in SciPy

A 2D integral, also known as a double integral, is a mathematical concept that involves finding the integral of a function over a two-dimensional region in the Cartesian plane.

How to Perform 2D Integrals in SciPy?

To perform 2D integrals using SciPy, you can use two methods dblquad() and nquad() that are defined in scipy.integrate module. The dblquad() method is used for double integration over a rectangular region while nquad() method is used for general multiple integrations.

In both methods, we can define a function called fun(x,y) as the function we want to integrate. We will then specify the integration limits for x and y using x_lower_limit, x_upper_limit, y_lower_limit, and y_upper_limit.

Let's discuss these methods in detail with examples.

Method 1: Using scipy.integrate.dblquad() Method

The dblquad() function is used to perform numerical integration of a function of two variables over a rectangular region. It is specifically designed for double integration. We use this function by passing our own defined function along with the integration limits as parameters to calculate the result and error of the 2D integral.

Python Program to Perform 2D Integrals Using dblquad() Method

# import dblquad from scipy integrate
from scipy.integrate import dblquad

# Defining the integrand function
def fun(x, y):
    return x**2 + y**2

# Define the integration limits
x_lower_limit = 0
x_upper_limit = 1
y_lower_limit = 0
y_upper_limit = 2

# Performing the double integration
result, error = dblquad(fun, 
    y_lower_limit, 
    y_upper_limit, 
    x_lower_limit, 
    x_upper_limit
    )

# Display result
print("Result:", result)
print("Error:", error)

Output

Result: 3.3333333333333335
Error: 4.7917013087034885e-14

Method 2: Using scipy.integrate.nquad() Method

The nquad() is used for performing numerical integration of multiple variables over a defined region. It allows you to compute N-dimensional integrals efficiently by automatically handling the nested integration. This function also requires the parameters in the form of the defined function and the integration limits.

Python Program to Perform 2D Integrals Using nquad() Method

# import nquad from scipy integrate
from scipy.integrate import nquad

# Defining the integrand function
def fun(x, y):
    return x**2 + y**2

# Define the integration limits
x_limits = (-1, 1)
y_limits = (-2, 2)

# Performing the double integration
result, error = nquad(fun, [x_limits, y_limits])

# Display result
print("Result:", result)
print("Error:", error)

Output

Result: 13.333333333333334
Error: 1.4802973661668756e-13

Python SciPy Programs »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.