Numerical Integration
• General Approximation Made With Num. Integration:
b n
∫ f(x) dx ≈ ∑ ci f(xi)
a i=0
• Integration finds the “Area” under
• Trapezoidal rule: a curve, between two points (a and b).
y
• To approximate the area under a curve,
f(b) use a familiar shape whose area we
already know how to calculate easily.
f(a) • In this case, we’ll use a trapezoid shape.
• Area of trapezoid = ½ (b1 + b2) h
base 2 (b1)
x
a b h
base 2 (b2)
Numerical Integration
• Trapezoidal
y
Rule (con’t):
• Area under curve ≈ Area of trapezoid
f(b) under the curve
f(a) • Area of trapezoid = ½ h [ b1 + b2 ]
• Area under curve ≈ ½ (b-a) [ f(a) + f(b) ]
• Therefore, Trapezoidal Rule:
x
b
a b
∫ f(x) dx ≈ ½ (b-a) [ f(a) + f(b) ]
a
• How can we get a better approximation of
the area under the curve?
• Answer: Use More Trapezoids
Numerical Integration
• More trapezoids give a better
approximation of the area under curve
y
• Add area of both trapezoids together,
f(b) more precise approx. of area under curve
f(x1)
f(a) • Area of trapezoid = ½ h [ b1 + b2 ]
• Area under curve ≈
x Area of Trapezoid 1 Area of Trapezoid 2
a x1 b ½ (x1-a) [ f(a) + f(x1) ] + ½ (b-x1) [ f(x1) + f(b) ]
Simplify:
½ ((b-a)/2) [ f(a) + f(x1) + f(x1) + f(b) ]
Area under curve ≈ (b-a) [ f(a) + 2 * f(x1) + f(b) ]
Numerical Integration
• Using more trapezoids to approximate
area under the curve is called: Composite
Trapezoidal Rule
• The more trapezoids, the better, so
instead of two trapezoids, we’ll use n
trapezoids.
• The greater the value of n, the better our
approximation of the area will be.
Composite Trapezoidal Rule
• Divide interval [a,b] into n equally spaced
subintervals (Add area of the n trapezoids)
b x1 x2 b
∫ f(x) dx ≈ ∫ f(x) dx + ∫ f(x) dx + … + ∫ f(x) dx
a a x1 xn-1
≈ (b-a)/2n [ f(x) + f(x1) + f(x1) + f(x2) +…+ f(xn-1) + f(b) ]
≈ (b-a)/2n [ f(x) + 2 f(x1) + 2 f(x2) +…+ 2 f(xn-1) + f(b) ]
b
∫ f(x) dx ≈ Δx/2 [ y0 + 2y1 + 2y2 + … + 2yn-1 + yn ]
a
Composite Trapezoidal Rule
Example 1 on Numerical Integration
• Implementing Composite Trapezoidal Rule in Matlab
• Example Curve: f(x) = 1/x , let’s integrate it from [e,2e] :
2e 2e
∫ 1/x dx = ln (x) | = ln (2e) – ln (e) = ln (2) = 0.6931
e e
Area under curve: 1/x, from [e,2e]
• Matlab Equivalent Inline(‘1/x’)
function I=Trapez(f, a, b, n) % take f, add n trapezoids,from a to b
% Integration using composite trapezoid rule
h = (b-a)/n ; % increment
s = feval(f,a) ; % starting value
for i=1:n-1
x(i) = a + i*h ; In our case, input to the function will be:
s = s+2 * feval (f,x(i)) ; f = inline (’1/x’)
end a = e = 2.7182818
s = s + feval(f,b) ; b = 2e
I = s*h/2 ;