quad() takes a Python function, a lower bound a, and an upper bound b, and returns a tuple of the estimated integral value and an estimate of the numerical error in that result — it uses adaptive quadrature internally, automatically subdividing the interval and using more evaluation points in regions where the function changes rapidly, to achieve high accuracy without you needing to specify a fixed number of sample points yourself. Either bound can be infinite, letting quad() handle improper integrals over an unbounded interval directly.
1Understanding integrate.quad()
quad() takes a Python function, a lower bound a, and an upper bound b, and returns a tuple of the estimated integral value and an estimate of the numerical error in that result — it uses adaptive quadrature internally, automatically subdividing the interval and using more evaluation points in regions where the function changes rapidly, to achieve high accuracy without you needing to specify a fixed number of sample points yourself. Either bound can be infinite, letting quad() handle improper integrals over an unbounded interval directly.
quad() returns a tuple of the result and an estimated error — a common mistake is treating its return value as just the integral result directly, forgetting to unpack the second element, or accidentally using the whole tuple where a single number was expected.
from scipy import integrate
import numpy as np
result, error = integrate.quad(lambda x: x**2, 0, 3)
print(result)2Practical Example
Here is a real-world application of integrate.quad() showing how it is used in production SciPy code.
from scipy import integrate
import numpy as np
result, error = integrate.quad(lambda x: np.exp(-x**2), -np.inf, np.inf)
print(round(result, 4))3Best Practices
Follow these guidelines when working with integrate.quad():
1. Always unpack both elements of quad()'s returned tuple, the integral value and the error estimate, rather than assuming it returns just a single number
2. Check the returned error estimate for functions that might be difficult to integrate accurately, very oscillatory, or with singularities, rather than blindly trusting the result
3. Pass an infinite bound directly for improper integrals over an infinite interval, instead of trying to approximate infinity with a very large finite number
Tip: quad() returns a tuple of the result and an estimated error — a common mistake is treating its return value as just the integral result directly, forgetting to unpack the second element, or accidentally using the whole tuple where a single number was expected.
from scipy import integrate
import numpy as np
result, error = integrate.quad(lambda x: x**2, 0, 3)
print(result)