triple integral in python

To perform a triple integral in Python, we can use the tplquad function from the scipy.integrate module. This function takes as input three functions representing the integrand, and the limits of the three integrals.

For example, let's say we want to evaluate the following triple integral:

∫∫∫(x^2 + y^2 + z^2) dxdydz

over the region 0 ≤ x ≤ 1, 0 ≤ y ≤ 1, and 0 ≤ z ≤ 1.

main.py
import numpy as np
from scipy.integrate import tplquad

def integrand(x, y, z):
    return x**2 + y**2 + z**2

def x_lower_limit(z, y):
    return 0

def x_upper_limit(z, y):
    return 1

def y_lower_limit(z):
    return 0

def y_upper_limit(z):
    return 1

def z_lower_limit():
    return 0

def z_upper_limit():
    return 1

result, error = tplquad(integrand, z_lower_limit, z_upper_limit, y_lower_limit, y_upper_limit, x_lower_limit, x_upper_limit)

print("Result:", result)
print("Error:", error)
505 chars
29 lines

In the code above, we first define the integrand function integrand(x, y, z) which represents the function (x^2 + y^2 + z^2).

We then define six other functions which represent the limits of integration of the three variables x, y and z. The functions x_lower_limit and x_upper_limit represent the lower and upper limits of integration of x, given the current values of y and z. Similarly, y_lower_limit and y_upper_limit represent the lower and upper limits of integration of y, given the current value of z, and z_lower_limit and z_upper_limit represent the lower and upper limits of integration of z.

Finally, we call the tplquad function with the integrand function and the six functions that represent the limits of integration. tplquad returns the value of the triple integral as well as the estimated numeric error.

Note that we can use numpy arrays or any other mathematical functions in the integrand and the limits of integration functions.

gistlibby LogSnag