8.1: Numerical Methods
- Page ID
- 14957
In Calculus, you learn how to use Riemann sums, the Trapezoidal Rule and Simpson’s rule to approximate definite integrals, which represent area under a curve for positive functions \(f(x)\).
The area between the function and the x-axis = \[\int_{a}^{b}f(x)\,dx\nonumber\]
Each involves finding the sum of areas of approximating shapes. Given a function f(x) defined on an interval [a, b], and a value n, the process is as follows.
- First subdivide the interval [a, b] into n equal subintervals.
- Assign x0 = a, x1 as the right endpoint of the first subinterval, x2 as the right endpoint of the second subinterval, · · · , xn as the right endpoint of the nth interval (that is xn = b).For example, if a = 0, b = 1, n = 4, then x0 = 0, x1 = .25, x2 = .5, x3 = .75 and x4 = 1. In this example, note that even though n = 4, there are five x values.
- Next, calculate the values f(x0), f(x1), f(x2), · · · , f(xn) by substituting the xi values into f(x).
The formulas for each of the methods are:
Riemann Sum: \[\int_{a}^{b}f(x)\,dx\approx \left ((b-a)/n\right )\left [ f(x_{0})+f(x_{1})+f(x_{2})+...+f(x_{n-2})+f(x_{n-1}) \right ]\nonumber\]
Trapezoidal Rule: \[\int_{a}^{b}f(x)\,dx\approx \left ((b-a)/2n\right )\left [ f(x_{0})+2f(x_{1})+2f(x_{2})+...+2f(x_{n-2})+2f(x_{n-1})+f(x_{n}) \right ]\nonumber\]
Simpson’s Rule: \[\int_{a}^{b}f(x)\,dx\approx \left ((b-a)/3n\right )\left [ f(x_{0})+4f(x_{1})+2f(x_{2})+...+2f(x_{n-2})+4f(x_{n-1})+f(x_{n}) \right ]\nonumber\]
Note
The pattern of coefficients in the Trapezoidal rule is 1, 2, 2, 2, · · · , 2, 2, 1 (each of the middle terms is a 2). In Simpson’s rule, the pattern is 1, 4, 2, 4, 2, 4, · · · , 2, 4, 2, 4, 1 where the middle terms start with a 4, alternate between 2 and 4, and end on a 4 (important!!). This last fact forces n to be an even number for Simpson’s rule to work.
Homework
Write a Matlab function with the following details.
- Name the function appropriately (mine could be siemerstj num methods)
- Comment the function appropriately including a description of the usage.
- The function should have three inputs a, b, n
- The function should have three outputs Rsum, Tsum, Ssum
- Once the function is run, a menu should appear with three choices of functions to choose from:
\[x^2, \sin x, \sqrt{\dfrac1{2π }}e^{{-x^2}/2}\nonumber\]
- Once the user clicks on a function from the menu, the function should compute the three approximations and output the values in a nice format (Hint: use fprintf).
- If n is not even, then only the Rsum and Tsum should be displayed with a message saying the Ssum could not be calculated.
Here is a sample run. Suppose I typed this :
>> [Rsum,Tsum,Ssum]=siemerstj num methods(0,1,6)
and then clicked on the x2 button in the menu. Then the output should be:
Rsum=.25463, Tsum=.3380, Ssum=0.33333