Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program in MATLAB to compute the approximate value for the derivative of

ID: 3628337 • Letter: W

Question

Write a program in MATLAB to compute the approximate value for the derivative of a function using the finite difference formula f(x)=f(x + h)-f(x)/h Test your program using the function tan(x) for x = 1. Determine the error by comparing your answer with the square of the MATLAB function sec(x) (since d/dx tan(x) = sec2x)). Plot the magnitude of the error as a function of h. for h m 10-k, k = 0,...,16. You should use logarithmic scale for h and the magnitude of the error. Is there a minimum value of the error? As h decreases how do rounding error and truncation error increase/decrease? Please include the printout of your MATLAB code.

Explanation / Answer

Copy and paste the blue into matlab:


%Set up a loop so you don't have to manually plug in lots of different h's
for k=0:16
    %Now define h
    h=10^-k;
    N=100; %Set the number of points you want to work with
   
   
    %Now set up your function so that x has spacing h
   
    x=0:h:N*h; % That gives us three periods to work with
    f=tan(x);
   
    %MatLab works very well with vectors, so we will do our derivative with
    %vectors instead of a Loop. In this case, f(x+h)=f(2:end);
    %f(x)=f(1:end-1) and h is still h.
    fprime=(f(2:end)-f(1:end-1))/h;
   
    %doing is this way tells it to do f(2)-f(1) and f(4)-f(3) and ...
    %all at once and is much faster.
   
    %We can define error as the sum of the difference squared divided by
    %the number of points, or more simply:
    err(k+1)=sum((fprime-sec(x(1:end-1))).^2)/N;
  
   
end

%now for the plot
%first we need an h vector
k=0:16;
h=10.^-k;
%Now make the plot
loglog(h,err,'b.')
xlabel('h')
ylabel('err')
title('Error in Finite Difference for Various h')

Notive how the error decreases until h is about 10^-15. After that matlab starts having floating point (roundoff) errors. That's why it starts going up again.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote