% The question from the book on Taylor's series. This was
% in the class. The bound that you obtain from the formula
% of the remainder given in the book gives you a very conservative bound of
% n=999 for the eror to be within 10^(-3). However, numerical calculation
% shows that by keeping n = 7 will suffice.
%
x = -0.5 : 0.01 : 0.5 ;     % These are the values of 'x' at which we evaluate the taylor series given by 'y' in the next line
y = zeros (1,length(x)) ;   % y is evaluated at each of the x values and therefore has the same length as 'x' above.

% loop goes from 1 to 7 only because I am considering the expansion upto
% only n=7..Note that the term in taylor expansion corresponding to n=0 is
% zero for this particular case so not considered here.

% temp below gives each term and then we add to to the value of y which is the Taylor series
% So for i=1 temp is the 2nd term corresonding to n=1 (as mentioned above, the first term corresponding to n=0 is zero)
% for i=2 temp is the 3rd term corresonding to n=2 and so on.
% The taylor polynomial for n=7 is the sum of all the terms.

for i = 1 : 7
    temp = (((-1)^(i+1))/i) * (x.^i)  ;
    y = y + temp ;
end
y;          % This can display the value of y if you remove semicolon. Remember y is a vector so do not display. This line is actually not required.
            % y will get stored in the workspace and its value can be accessed at whatever value you want.

value = log(1+x) ;
z = abs (value - y) ;       % This gives the error 'z' between the actual value 'value' and the taylor approximation 'y'.
disp ('max error is') ; max(z)                       % This can display the max value of the error 'z'. Remember 'z' is also an array. Note, there is no semicolon here.

% The two lines below are not actually required. They just give the value of the bound that we obtain manually.
n=999;
rem = (x.^(n+1))./((n+1).*((0.5)^(n+1)));

% Here we plot the figures.
% Figure(1) plots Taylor approximation 'y' Vs 'x'in red and Actual value of the function 'value' Vs 'x' in blue
figure (1) ;
plot (x,y,'r',x,value,'b') ;
grid on ;
figure (2) ;        % This plots error 'z' Vs 'x' in black.
plot (x,z,'k') ;
grid on ;
max error is

ans =

  8.8528e-004