MATLAB, the derivative f?(x) of a differentiable function f(x) can be approximat
ID: 638476 • Letter: M
Question
MATLAB, the derivative f?(x) of a differentiable function f(x) can be approximated by a finite difference formula. Two such formulas are the forward difference
and the centered difference
where h is a (small) positive real number.
(a) Write two Matlab functions with definitions fp = fdiff(f,x,h) and
fp = cdiff(f,x,h) implementing the forward difference formula and the centered difference formula respectively. In both cases, the input f is an arbitrary function passed using the @ notation, x is a vector of values at which to approximate the derivative, and h is a positive scalar. The output fp is an approximation to the derivative. Do not use a for loop in your functions.
(b) Use your functions from part (a) to approximate the derivative of f(x) = 1/(1+x^2) on the interval [?1, 1]. Take x = linspace(-1,1,100) and h = 1e-4. Prepare the following plot having two subplots by using the built-in commands subplot(2,1,1) and subplot(2,1,2). The top plot should depict the absolute value of the error between the forward difference approximation and the exact derivative. The bottom plot should depict the absolute value of the error between the centered difference approximation and the exact derivative.
(c) Now, take f(x) = e^x and h = 10?1,10?2,...,10?9. Approximate f?(0) using the two finite difference formulas from part (a) at each value of h. The exact value is obviously f?(0) = 1. Make a table which lists h in the first column, the forward difference approximation in the second column, the error in the forward difference approximation in the third column, the centered difference approximation in the fourth column, and the error in the centered difference approximation in the fifth column. Report h in scientific notation with the minimum number of displayed digits. Report errors in absolute value using scientific notation, keeping 3 digits past the decimal. Approximations should be reported in fixed-point non-scientific notation with a full field of digits (say 14 past the decimal point).
(d) Plot the errors from part (c) versus h on the same log-log plot. Your plot should include a legend. What do you observe?
Explanation / Answer
clear %the function f = @(x) 25*x^3-6*x^2+7*x-88; %actual derivative of function fprime = @(x) 75*x^2-12*x+7; %step size: h=0.25; %forward difference dfdx_forward = (f(2+h)-f(2))/h Error_forward = fprime(2)-dfdx_forward %error %bacward difference dfdx_backward = (f(2)-f(2-h))/h Error_backward = fprime(2)-dfdx_backward %error %central difference dfdx_central = (f(2+h)-f(2-h))/(2*h) Error_central = fprime(2)-dfdx_central %error
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.