To compute the central difference approximation for a function f, we use the following formula:
We can write a script in MATLAB to calculate the central difference approximation for a vector of increasingly smaller values of h as follows:
main.m668 chars27 linesIn this script, we define the function central_diff to calculate the central difference approximation using the formula given above. We then define the function f that we want to approximate the derivative of, as well as the point at which we want to compute the derivative x0.
We define the vector h_vec containing the values of h that we want to use for the approximation, and initialize a vector df_vec to store the results. We use a for loop to compute the approximation of f'(2) for each value of h, and store the results in df_vec.
Finally, we plot the error in the approximation vs. h using a logarithmic scale for both axes. We use the fact that f'(2) = 2*cos(2) + 4 to compute the exact value of the derivative at x0, and plot the absolute value of the error. We can see from the plot that the error decreases as h gets smaller, as expected.
gistlibby LogSnag