0
0
SciPydata~5 mins

Double integral (dblquad) in SciPy

Choose your learning style9 modes available
Introduction

We use double integrals to find the total value of something spread over a flat area, like the total heat on a metal plate or the total rainfall over a region.

Calculating the total mass of a thin sheet with varying density.
Finding the total amount of rainfall over a rectangular area.
Determining the total heat energy distributed over a surface.
Computing the area under a surface defined by a function of two variables.
Syntax
SciPy
scipy.integrate.dblquad(func, a, b, gfun, hfun)

# func: function to integrate, takes two variables (y, x)
# a, b: limits for x (outer integral)
# gfun, hfun: functions giving lower and upper limits for y (inner integral), each takes x

The function func must have the order of variables as func(y, x), not func(x, y).

The limits a and b are for the outer integral (x), and gfun and hfun define the inner integral limits (y) depending on x.

Examples
This calculates the integral of x + y over the square from 0 to 1 in both x and y.
SciPy
from scipy.integrate import dblquad

# Integrate f(x,y) = x + y over x=0..1 and y=0..1
result, error = dblquad(lambda y, x: x + y, 0, 1, lambda x: 0, lambda x: 1)
This integrates over a triangular region where y goes from 0 to x.
SciPy
from scipy.integrate import dblquad

# Integrate f(x,y) = x*y over x=0..2 and y=0..x
result, error = dblquad(lambda y, x: x * y, 0, 2, lambda x: 0, lambda x: x)
Sample Program

This program calculates the double integral of the function x² + y² over the square area where both x and y go from 0 to 1.

SciPy
from scipy.integrate import dblquad

# Define the function to integrate: f(x,y) = x**2 + y**2
func = lambda y, x: x**2 + y**2

# Set the limits for x: 0 to 1
x_lower = 0
x_upper = 1

# Set the limits for y: 0 to 1
y_lower = lambda x: 0
y_upper = lambda x: 1

# Perform the double integral
result, error = dblquad(func, x_lower, x_upper, y_lower, y_upper)

print(f"Double integral result: {result}")
print(f"Estimated error: {error}")
OutputSuccess
Important Notes

The order of variables in the function is important: it must be func(y, x), not func(x, y).

The limits for the inner integral (y) can depend on the outer variable (x), allowing integration over irregular shapes.

The function returns two values: the integral result and an estimate of the error.

Summary

Double integrals calculate totals over 2D areas.

Use scipy.integrate.dblquad with the function, outer limits, and inner limits.

Remember the function takes variables in the order (y, x), and inner limits can depend on x.