% this is a matlab solution file for Math 126 worksheet of 1/11/12. Barnett

% A:
x = -1:0.01:1;   % note created first
y = exp(x);
figure; plot(x,y, '-'); xlabel('x'); title('exp function');

% B: (continues to use above variables...)
z = 0*x;    % allocate a set of values to sum the Taylor series into
for n=0:10    % note, starts at zero
  z = z + x.^n / factorial(n);   % note .^ since elementwise power
end
figure; plot(x,z-y, '-'); xlabel('x'); ylabel('error');  % plot error

% C: one way is to loop over n explicitly
x = 1.0; % replace our ordinate by this single value
M = 50;   % max Taylor order
z = zeros(1,M);  % allocate answers at all the truncation orders
z(1) = 1 + x; % 0th and 1st terms do ahead of the loop
for n=2:M    % note z(n) is the sum up to and including nth term
  z(n) = z(n-1) + x.^n / factorial(n);
end
figure; semilogy(1:M, abs(z-exp(x)), '+-'); % use log y scale to show small errs
xlabel('N'); ylabel('error'); axis([1 M 1e-16 1e0]) 
% note errors are exactly zero from n>16 !

% C: doing it the fancy way - using vectorized factorial and power, summing
% (cumulatively) at the end only
x = 1.0;
n = 0:50;
z = cumsum(x.^n./factorial(n));
figure; semilogy(n, abs(z-exp(x)), '+-'); xlabel('N'); ylabel('error');
