0
0
SciPydata~5 mins

Triple integral (tplquad) in SciPy

Choose your learning style9 modes available
Introduction

We use triple integrals to find the total amount of something in a 3D space, like volume or mass.

Calculating the volume of a 3D shape when the boundaries are complex.
Finding the total mass of an object with varying density inside a 3D region.
Computing the total charge in a 3D space with a charge density function.
Determining the amount of heat inside a solid with temperature varying in all directions.
Syntax
SciPy
scipy.integrate.tplquad(func, a, b, gfun, hfun, qfun, rfun)

# func: function to integrate, takes (z, y, x)
# a, b: limits for x
# gfun, hfun: functions for y limits, depend on x
# qfun, rfun: functions for z limits, depend on x and y

The order of variables in func is z, y, x, which is different from usual math order.

Limits can be constants or functions depending on outer variables.

Examples
Integrate x*y*z over the cube where x, y, z go from 0 to 1.
SciPy
from scipy.integrate import tplquad

def f(z, y, x):
    return x * y * z

result, error = tplquad(f, 0, 1, lambda x: 0, lambda x: 1, lambda x, y: 0, lambda x, y: 1)
print(result)
Calculate volume of a pyramid bounded by planes using triple integral.
SciPy
from scipy.integrate import tplquad

def f(z, y, x):
    return 1

# Volume of a pyramid with x from 0 to 1,
# y from 0 to x, z from 0 to y

result, error = tplquad(f, 0, 1, lambda x: 0, lambda x: x, lambda x, y: 0, lambda x, y: y)
print(result)
Sample Program

This program calculates the total mass of a box where density changes with x, y, and z.

SciPy
from scipy.integrate import tplquad

def density(z, y, x):
    # Density varies with position
    return x + y + z

# Limits:
# x from 0 to 1
# y from 0 to 2
# z from 0 to 3

result, error = tplquad(density, 0, 1, lambda x: 0, lambda x: 2, lambda x, y: 0, lambda x, y: 3)

print(f"Total mass: {result:.2f}")
OutputSuccess
Important Notes

Remember the order of variables in the function is z, y, x, not x, y, z.

Use lambda functions to set limits that depend on outer variables.

Check the error estimate returned by tplquad to understand accuracy.

Summary

Triple integrals calculate totals over 3D spaces.

tplquad in SciPy helps compute these integrals easily.

Limits can be constants or functions depending on other variables.