% -*- octave -*-
%
% Matlab function for approximating the sine function using a truncated
% Taylor's series. The value of x is given as an argument to the
% function and the function returns the approximation to sin(x).
%
% Copyright (c) 1999, Eric S Fraga, UCL, All rights reserved.
%
function y = sine(x)
  %
  % specify the values of some variables that will be used to control
  % the iterations performed by the taylor series evaluation
  %
  maxiters = 1000;		% no more than 1000 iterations
  tolerance = 1e-5;		% accurate to this value
  %
  % initialize some variables used by the taylor series:
  %
  % y - the current approximation to sin(x) and value returned
  % f - the factorial term in the taylor series expansion
  % i - the index for taylor series expansion
  %
  y = 0.0;
  f = 1.0;			% equivalent to 1!
  i = 0;

  % loop, evaluating each term in the sum expansion of sin(x). this
  % iteration continues until we either exceed the number of iterations
  % or the tolerance is met. the tolerance is met when successive
  % values of the approximation differ by less than the tolerance value
  % given above

  while (i < maxiters)
    oldy = y;			% remember old value
    % evaluate the taylor series term and add it to the current value
    % of the approximation (note, we leave the semi-colon off the end
    % of the line so that Matlab/Octave will output the value of y in
    % each iteration!)
    y = y + (-1)^i * x^(2*i+1)/f
    % check to see if the tolerance specification has been met
    if ( abs(y - oldy) < tolerance )
      return			% tolerance has been achieved
    end
    % iterate again so we prepare the variable F which contains the
    % factorial term and also increase the value of the I variable
    f = (2*i+2) * (2*i+3) * f;
    i = i + 1;
  end

  disp('Number of iterations allowed has been exceeded')
end
