% ttaylorsin Driver script for taylorsin [PHYS210-HW3]
%
%  Uses taylorsin to compute an approximation of sin(x) for x = 0 .. pi
%  using a maximum of 5 and 10 terms.  Computes and plots errors.

% Define x values.

nx = 101;
x = linspace(0.0, pi/2, nx);

% Define vectors for approximations.

sinx_5 = zeros(1, nx);
sinx_10 = zeros(1, nx);

% Define the tolerance for the series calculation; taylorsin will
% sum the series until the magnitude of the term being computed 
% is <= tol, or some maximum specified number ot terms have been
% calculated (5 and 10 in this demonstration).
%
% Recall that eps -> "machine epsilon" -> smallest 
% floating point number such that 1 + eps ~= 1.  With standard 
% 8 byte arithmetic, eps is ~ 10^{-16}, so we are trying to compute 
% approximations with about 14 digits accuracy.

tol = 100 * eps;

for ix =  1 : nx
   sinx_5(ix) = taylorsin(x(ix), tol, 5);
   sinx_10(ix) = taylorsin(x(ix), tol, 10);
end

% Compute errors for all values of x where the series calculations
% converged.  Note the use of the functions: 
%
%  (1) isnan(X) which returns 1 / 0 if X is / isn't a NaN - note that
%      taylorsin returns NaN when the approximation did NOT converge
%      to the requested tolerance within the maximum number of 
%      iterations allowed.
% 
%  (2) find (see the tfind script for a commented example, find is very
%      useful and well worth knowing a bit about).

x_5 = x(find(~isnan(sinx_5)));
x_10 = x(find(~isnan(sinx_10)));
e_5 = sinx_5(~isnan(sinx_5)) - sin(x_5)
e_10 = sinx_10(~isnan(sinx_10)) - sin(x_10)

% Make the plot.

figure(1);
clf;
hold on;
plot(x_5, e_5, 'ro');
plot(x_10, e_10, 'b+');
title('Error in Taylor series approximation of sin(x)');
xlabel('x');
ylabel('Error');
legend('5 terms', '10 terms', 'location', 'best');
