%
%   TRADEOFF.M  Show trade-off in truncation and round off error when solving
%                  a simple IVP:   y' = exp(x)   with  y(0) = 1
%   (used to generate plot of error vs step size for Fig. 1 in Lesson 4 Lecture Notes)
%
%   Written by J. R. White, UMass-Lowell (last update: Oct. 2017)
%

      clear all,   close all
%
%   set different step sizes (decreasing by a factor of 10)
%   this is what I really want  (note h = 1e-10 only works for 64-bit machines)
      h = [1e-1 1e-2 1e-3 1e-4 1e-5 1e-6 1e-7 1e-8 1e-9 1e-10]';     
%   use the next line for debugging (this runs in a minute or so) -- comment out 
%   for real case
%     h = [1e-1 1e-2 1e-3 1e-4 1e-5 1e-6 1e-7 1e-8 ]';   
      N = round(2./h);                   % number of steps
%
%   solve IVP for each h
      xf = zeros(size(h));    yf = zeros(size(h));  
      rerr = zeros(size(h));  time = zeros(size(h));
      for n = 1:length(h)
        t = clock;                       % start timer
        x = 0;  y = 1;                   % initial conditions
        for i = 1:N(n)
          y = y + exp(x)*h(n);           % increment y
          x = x + h(n);                  % increment x
        end
        time(n) = etime(clock,t);        % elasped time (s)
        xf(n) = x;   yf(n) = y;          % final conditions
        rerr(n) = abs((yf(n)-exp(2))/exp(2)); % absolute relative error at xf = 2
      end
%    
%   create short table of results
      fprintf('       h             N                  xf                   yf           rel error     time(s)\n')
      for n = 1:size(h)
        fprintf('  %10.2e   %13i   %18.10e   %18.10e   %10.2e   %10.2e \n', ...
                h(n),N(n),xf(n),yf(n),rerr(n),time(n));
      end
      fprintf('\n   The exact result should be yf = exp(2) = %20.10e \n',exp(2));
%
%   make plot of results
      loglog(h,rerr,'ro','LineWidth',2),grid
      title('TradeOff:  Relative Error vs Step Size for given IVP -- y'' = e^x with y(0) = 1')
      xlabel('Step Size'), ylabel('Relative Error in y_f = y(x_f) = y(2)')
%
%  end of problem