% Rate of Change
% Sample MATLAB Program

% Approximates the instantaneous rate of change of
% the function f
% at the point x=a
% to within epsilon


syms('x');   % uses a symbolic expression - can also use a function m-file

f=sin(x);    % the function to be analyzed
a=0;         % the x-value of the point of interest
epsilon=.000001; % desired accuracy

bound=epsilon+1;   % just makes sure the while loop runs at least once
h=.1;              % initial delta x
while bound>epsilon
    LeftApprox=(subs(f,a)-subs(f,a-h))/h     % one approximation
    RightApprox=(subs(f,a+h)-subs(f,a))/h    % another approximation
    bound=abs(LeftApprox-RightApprox);       % bound on the error
    h=h/10;        % decrease h to make it more accurate
end
Approx=(LeftApprox+RightApprox)/2;                   % use the average
fprintf('The rate is approximately %g',Approx);      % output