% Script File TaylorError
%
% Plots, as a function of n, the relative error in the 
% Taylor approximation
%
%   1 + x + x^2/2! +...+ x^n/n!                         to      exp(x),
%   2*Sum(((((x-1)/(x+1))^(2n-1))/(2n-1))), n=1,2,3..   to      log(x),
%   x-x^3/3!+x^5/5!-x^7/7!+...                          to      sin(x).
%
% nTerms = 150
% x=[0.01, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0]

   close all
   nTerms = 150;
   c=1;
   digits=6;
   for x=[0.01, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0]
      exp_error = exp(x)*ones(nTerms,1);
      exp_s = 1;
	  exp_term = 1;
      log_error = log(x)*ones(nTerms,1);
      log_s = (x-1)/(x+1);
      log_top = (x-1)/(x+1);
      sin_error = sin(x)*ones(nTerms,1);
      sin_s = x;
      sin_term = x;
      for k=1:nTerms
         exp_term = x*exp_term/k;
         exp_s = exp_s+ exp_term;
         exp_error(k) = abs(exp_error(k) - exp_s);
         log_top = log_top*((x-1)/(x+1))^2;
         log_term = log_top/(2*k+1);
         log_s = log_s+log_term;
         log_error(k) = abs(log_error(k)-2*log_s);
         sin_term = sin_term*-x^2/(4*k^2+2*k);
         sin_s = sin_s + sin_term;
         sin_error(k) = abs(sin_error(k) - sin_s);
      end;
	  exp_relerr = exp_error/abs(exp(x));
      exp_sig = -log10(exp_relerr(150));
      log_relerr = log_error/abs(log(x));
      log_sig = -log10(log_relerr(150));
      sin_relerr = sin_error/abs(sin(x));
      sin_sig = -log10(sin_relerr(150));
      subplot(3,3,c), semilogy(1:nTerms,exp_relerr,'r-', 1:nTerms,log_relerr,'b-', 1:nTerms,sin_relerr,'g-')
      ylabel('relative error')
      title(sprintf('x = %5.2f, \n expSig = %2.0f, logSig = %2.0f, sinSig = %2.0f',x, exp_sig, log_sig, sin_sig))
      c=c+1;
   end
   
   

