%
%   PS_DEMO1.M   Evaluation of Infinite Power Series Expansions
%
%   This demo simply illustrates how to evaluate an infinite series
%   expansion for a particular function, f(x), as discussed in Section VII
%   of the Math Methods notes.  The key here is to write the series as a simple
%   recurrence relation, with term Tn+1 written as a function of term Tn (see 
%   the notes for details).
%
%   File prepared by J. R. White, UMass-Lowell (Aug. 2003)
%

%
%   getting started
      clear all,  close all,   nfig = 0;
%
%   define range of x values (be sure to stay within the radius of convergence)
      x = linspace(0,1.8,50);
%
%   NOTE: For this problem the series converges for |x| < 2.  Just to see what happens
%   when you ignore this fact, you might try setting the maximum x to 2.1 (instead of 1.8).
%
%   loop over terms in expansion
      maxT = 101;  tol = 1e-6;   n = 0;  mrerr = 1.0;
      T = 1;  f = T;                   % initialize series
      while mrerr > tol  &  n < maxT
        r = - (1/8)*x.^3;              % compute r  (this is usually a function of n)
        T = r.*T;                      % compute Tn+1
        f = f + T;                     % add Tn+1 to partial sum
        i = find(f);                   % finds indices of nonzero values of f
        mrerr = max(abs(T(i)./f(i)));  % compute max relative error
        n = n+1;                       % increment counter
      end
      NT = n;                          % number of terms used in expansion
%
%   plot results
      nfig = nfig+1;   figure(nfig)
      plot(x,f,'b-','LineWidth',2), grid
      title(['PS\_Demo1:  Evaluating Infinite Series Expansions (NT = ',num2str(NT), ')']); 
      xlabel('x values'),ylabel('f(x) values')
%
%   end of program
