%% Mfile name % test_mydiff.m %% Revised: % October 2, 2007 %% Purpose % Testing the mydiff function to find the the first derivative of the % function at x within a prespecified percentage tolerance tol and a % starting step size of dx. The function uses forward divided difference % method. %% Usage % fp=mydiff(f,x,dx,tol) % Input variables % f = function % x = point at which derivative of f is sought % dx = starting step size % tol = prespecified percentage tolerance % Output variables % fp = approximate value of derivative of f at point x % Keyword % Differentiation % Forward Divided Difference % Author % Autar Kaw % Section: All % Semester: Fall 2007 clc disp('Name: Autar Kaw') disp('Section: All') %% Test 1 %Test#1 to see if the procedure works for prespecified tolerance being small % For a tolerance of 0.000005%, find the derivative of 2*exp(1.5*x) at % x=2.5 with a starting step size of 0.2. We should get results close to % the exact value disp ('Test#1') tol=0.000005; fprintf ('\nTolerance = %g\n', tol) y=2.5; fprintf ('Value at which derivative is to be found = %g\n', y) dy=0.2; fprintf ('Starting value of step size=%g\n', dy) g=inline('2*exp(1.5*x)'); fun_string=['Function of which derivative is found is f=' char(g)]; fprintf(fun_string) % Value obtained using my own differentiation routine fpvalue=mydiff(g,y,dy,tol); fprintf ('\n\nApproximate value of derivative= %g\n', fpvalue) % Value obtained using exact differentiation of matlab syms x; f=2*exp(1.5*x); fpexact=subs(diff(f,x),y); fprintf ('Exact value of derivative= %g\n', fpexact) disp('_________________________________________________________') %% Test 2 %Test#2 to see if the procedure works for prespecified tolerance being small % For a small tolerance of 0.5%, find the derivative of 2*exp(1.5*x) at % x=2.5 with a starting step size of 0.2. % We should get results NOT close to exact value. disp ('Test#2') tol=0.5; fprintf ('\nTolerance = %g\n', tol) y=2.5; fprintf ('Value at which derivative is to be found = %g\n', y) dy=0.2; fprintf ('Starting value of step size=%g\n', dy) g=inline('2*exp(1.5*x)'); fun_string=['Function of which derivative is found is f=' char(g)]; fprintf(fun_string) % Value obtained using my own differentiation routine fpvalue=mydiff(g,y,dy,tol); fprintf ('\n\nApproximate value of derivative= %g\n', fpvalue) % Value obtained using exact differentiation of matlab syms x; f=2*exp(1.5*x); fpexact=subs(diff(f,x),y); fprintf ('Exact value of derivative= %g\n', fpexact) disp('_________________________________________________________')