M371 - Alexiades
Lab 4
Finite Difference approximation to derivatives
Write a code to approximate the derivative of a function f(x)
using forward finite difference quotient
f( x + h ) - f( x )
f'(x) ≈ ------------------- (for small h).
h
For the function f(x) = sin(x), at x=1 , compute the FD quotients for
h = 1/2k, k=5,...,N, with N=30
and compare with the exact derivative cos(x).
Output k , h , error.
1. Where SHOULD the error tend as h → 0 ?
Look at the numbers. Does the error behave as expected ?
Output to a file "out" (or to arrays in matlab), and plot it
[ gnuplot> plot "out" u 2:3 with lines ]
Which direction is the curve traversed, left to right or right
to left ?
Look at the numbers. h is decreasing
exponentially, so the points pile up on the vertical axis.
The plot is poorely scaled. To see what's happening, use logarithmic
scale,
i.e. output k , log(h) , log(error) and replot.
2. What is the minimum error ? at what k ?
Why does the error get worse for smaller h ?
3. Repeat, using centered finite differences
[copy your code to a another file and modify it]
f( x + h ) − f( x − h )
f'(x) ≈ ----------------------- (for small h).
2 h
4. Which formula performs better ? in what sense ?
Submit the following, in a plain text file Lab4.txt
Lab 4: NAME , date
*************************************************
a. Answers to 2 for Forward FD:
=================================================
b. Answers to 2 for Centered FD:
=================================================
c. Answers to 4.
*************************************************
d. your code for centered FD (cleaned up!)