How to calculate definite integral in Python

Definite integrals are fundamental in mathematics, physics, and engineering. Python offers multiple libraries for exact and numerical integration. This guide covers four primary methods: symbolic integration with SymPy, numerical quadrature with SciPy, arbitrary-precision integration with mpmath, and discrete approximation with NumPy.

1. Symbolic Integration with SymPy

Use sympy.integrate for exact antiderivatives and definite integrals.

from sympy import symbols, integrate, sin

x = symbols('x')
expr = sin(x)**2

# Definite integral from 0 to pi
result = integrate(expr, (x, 0, 3.141592653589793))
print(result)  # pi/2
  

Tip: SymPy handles a wide range of symbolic integrals but may be slow for complex expressions.

See also  Exponential Regression with NumPy

2. Numerical Quadrature with SciPy

scipy.integrate.quad uses adaptive algorithms for high-accuracy numerical integration.

import numpy as np
from scipy.integrate import quad

# Integrand
def f(x):
    return np.sin(x)**2

# Compute integral
result, error = quad(f, 0, np.pi)
print(f"Result: {result:.6f}, Error estimate: {error:.2e}")  # ~1.570796, ~0
  

Note: quad returns both value and error estimate. For oscillatory or singular functions, consider quadpack options.

3. Arbitrary-Precision Integration with mpmath

mpmath.quad supports arbitrary precision and complex integrals.

import mpmath as mp

mp.mp.dps = 50  # 50 digits precision

def g(x):
    return mp.exp(-x**2)

# Integrate from 0 to infinity
result = mp.quad(g, [0, mp.inf])
print(result)  # ~0.886226925...
  

Tip: Use mp.quad with piecewise intervals ([a,b]) for infinite limits.

See also  How to stack arrays in Numpy?

4. Discrete Approximation with NumPy

Approximate integrals using the trapezoidal rule with numpy.trapz.

import numpy as np

x = np.linspace(0, np.pi, 100000)
y = np.sin(x)**2

# Trapezoidal rule
result = np.trapz(y, x)
print(result)  # ~1.570796
  

Note: Increase sample points for higher accuracy. For Simpson’s rule, use scipy.integrate.simpson.

Comparison of Methods

Method Use Case Accuracy Performance
SymPy Exact symbolic integrals Exact Slow for complex
SciPy quad General numerical Machine precision Fast
mpmath High-precision or complex Arbitrary Moderate
NumPy trapz Quick approximations Depends on sampling Very fast
See also  How to resolve ValueError: operands could not be broadcast together with shapes

Summary Checklist

  1. Use SymPy for closed-form results.
  2. Use SciPy quad for reliable numerical integration.
  3. Use mpmath for high-precision or complex path integrals.
  4. Use NumPy trapz for quick, large-scale approximations.