HW 4, problem 2.2 parts a-e

 

By Nasser Abbasi

 

SOURCE CODE

function nma_HW2_2_other_parts(problemPart,x)

%function nma_HW2_2_error_other_parts

%

% finds the error in calculation of derivatives for a number

% of functions as a function of delta, at some specific points.

%

% INPUT

%   problemPart  : a character of the name of the part, a-e

%   x            : the value to evalute the derivative at.

%

% This is the solution to problem 2.2, parts a-e.

%

%

 

%HW 4, 2.2 parts a-e

%Nasser Abbasi, phy 240, Sam Jose State Univ.

%Feb 6, 2002

 

% struct to hold the data as we iterate

struct err { ...

   value   : 0 ...

   delta   : 0 };

  

switch(problemPart)

  case 'a'

      deriveExact=2*x;

      process('fa',problemPart,x,deriveExact);

      return;

  case 'b'

      deriveExact=5*x^4;

      process('fb',problemPart,x,deriveExact);

      return;

  case {'c','d','e'}

      deriveExact=cos(x);

      process('fc',problemPart,x,deriveExact);

      return;

   error('invalid part number');

end

 

%%%%%%%%%%%%%%%%%%%%%%%%%%

%

%

%%%%%%%%%%%%%%%%%%%%%%%%%%

function process(functionName,problemPart,x,exact)

  

delta =1;

 

for i=1:21       

     deriveApprox  = ( feval(functionName,x+delta) - feval(functionName,x)) / delta;

     err.value(i)    = abs(exact - deriveApprox);

     err.delta(i)    = delta;   

     delta = delta/10;

end

 

p=loglog(err.delta,err.value,'.');

 

title(sprintf('Showing abs error in evaluation of derivative for part %c at x=%d',problemPart,x));

xlabel('Delta, or step size, drawn on a log scale.');

ylabel('Absolute error, drawn on a log scale');

 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% function x^2, for part a

%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [y]=fa(x)

y=x^2;

 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% function x^5 for part b

%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [y]=fb(x)

y=x^5;

 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% function sin(x) for part c

%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [y]=fc(x)

y=sin(x);

 


 

OUTPUT

 

» clear all

» help nma_HW2_2_other_parts

 

 function nma_HW2_2_error_other_parts

 

  finds the error in calculation of derivatives for a number

  of functions as a function of delta, at some specific points.

 

  INPUT

    problemPart  : a character of the name of the part, a-e

    x            : the value to evalute the derivative at.

 

  This is the solution to problem 2.2, parts a-e.

 

 

» nma_HW2_2_other_parts('a',1)

» nma_HW2_2_other_parts('b',1)

» nma_HW2_2_other_parts('c',0)

» nma_HW2_2_other_parts('d',pi/4)

» nma_HW2_2_other_parts('e',pi/2)