Have you ever wondered how to calculate the area under a curve when there’s no simple formula for it? 🤔
That’s where numerical integration comes in — a powerful method that allows us to approximate definite integrals using a computer.
In this beginner-friendly article, you’ll learn:
- What numerical integration is
- The most popular methods used
- How to implement them in Python step-by-step
- Practical examples to solidify your understanding ✅
🔍 What is Numerical Integration?
Numerical integration is a method to approximate the value of a definite integral when:
- An exact analytical solution is hard or impossible to compute
- The function is too complex or unknown in closed form
✳️ Goal: Estimate the area under a curvef(x)
between two pointsa
andb
📐 Common Methods of Numerical Integration
- Rectangle Rule
- Trapezoidal Rule
- Simpson’s Rule (more accurate, requires even intervals)
💻 Practical Implementation in Python
1. Required Libraries
import numpy as np
from scipy.integrate import quad
2. Using scipy.integrate.quad
(the easiest way)
# Define the function
def f(x):
return x**2 + 3*x + 1
# Integration limits
a = 0
b = 5
# Numerical integration
result, error = quad(f, a, b)
print(f"📌 Approximate result: {result:.4f}")
print(f"🔍 Estimated error: {error:.2e}")
Expected output:
📌 Approximate result: 91.6667
🔍 Estimated error: 1.02e-13
✏️ Manual Implementation: Trapezoidal Rule
def trapezoidal(f, a, b, n):
h = (b - a) / n
result = 0.5 * (f(a) + f(b))
for i in range(1, n):
result += f(a + i * h)
return result * h
# Test
approx = trapezoidal(f, 0, 5, 100)
print(f"Trapezoidal (n=100): {approx:.4f}")
📊 Method Comparison
Method | Simplicity | Accuracy | Use in Programming |
---|---|---|---|
Rectangle | ⭐⭐ | Low | Educational only |
Trapezoidal | ⭐⭐⭐ | Medium | Easy to implement |
Simpson’s | ⭐⭐⭐⭐ | High | Great if available |
scipy.quad | ⭐⭐⭐⭐⭐ | Very High | Best for production |
📈 When to Use Numerical Integration?
- In physics simulations
- To compute areas or curve lengths
- In data science and engineering modeling
🧩 Summary
Numerical integration is an essential tool in programming and applied mathematics, especially when analytical integration is not feasible.
Th