% taylor_sine.m
%  Plot the N-term Taylor series for y=sine(x).
%
%  exp(x) = 0 + x/1 + 0 - x^3/3! + 0 + x^5 / 5! + 0 - x^7 / 7! + ...
%
n = input ( 'Enter the maximum Taylor polynomial degree. ' );
a = input ( 'Enter the lower X limit (such as 0): ' );
b = input ( 'Enter the upper X limit (such as 1): ' );
%
%  Create a list of 101 equally spaced x values between a and b.
%
dots = 101;
x = linspace ( a, b, dots );
f = sin ( x );
p = zeros ( 1, dots );
%
%  There is a "stepping stone" rule for the next term to add.
%    Term(i) = Term(i-1) * x / i
%
clf
hold on
%
%  Plot the sine curve.
%
plot ( x, f, 'b-', 'linewidth', 3 );
axis ( [ a, b, -1.0, +1.0 ] )
grid on
xlabel ( '<-- X -->' );
ylabel ( '<-- Y -->' );

for i = 1 : 2 : n
%
%  Remove previous graph.
%
  if ( 0 < i )
    plot ( x, p, 'w-', 'linewidth', 3 );
  end
%
%  x^i/i! = x^(i-2)/(i-2)! * ( x^2 / i / (i-1) )
%
  if ( i == 1 )
    term = x;
    p = term;
  elseif ( mod ( i, 2 ) == 1 ) 
    term = - term .* x .* x / i / ( i - 1 );
    p = p + term;
  end
%
%  Plot the new Taylor polynomial.
%
  plot ( x, p, 'r-', 'linewidth', 3 );
  string = sprintf ( 'Polynomial of degree %d', i );
  title ( string );
  if ( i < n )  
    disp ( 'Press RETURN for next plot:' );
    pause;
  else
    disp ( 'That''s all!' );
  end

end
%
%  Save a JPG copy of the last plot.
%
print ( '-djpeg', 'taylor_sine.jpg' );

hold off
