function ex3_1(a,xleft,xright)
% Function to plot the Taylor approximations of fx = sqrt(x)
% Example 3.1
% Syntax: ex3_1(a,xleft,xright)
%           a = base point of Taylor expansion
%           xleft,xright = min and max limits of interval
%
% To produce the plots for Example 3.1, call the function with
%  ex3_1(4,3,4)

% Check for input error and fix it
if xleft>xright
    dummy = xleft;
    xleft = xright;
    xright = dummy;
end

% Close all figures to avoid superimposing on old figures
close all

% Create an array of uniformly spaced points on the interval
x = linspace(xleft,xright,20);

% Exact Function
fx = x.^(1/2);  %Array of exact values

% Store intermediate values
h = x-a;
f0 = (a^(1/2))*ones(size(x));

% defining the function by Taylor series expansions
f1x = f0 + 1/(2*sqrt(a))*h;         % 1st order approximation
f2x = f1x - 1/(4*a*sqrt(a))*(h.^2)/2;      % 2nd order approximation
f3x = f2x + 3/(8*a^2*sqrt(a))*(h.^3)/6;   % 3rd order approximation

% Plotting the exact function and polyomials against x
figure(1)
plot(x,fx,'-k',x,f1x,x,f2x,x,f3x);
axis([xleft,xright,1.5,2.25])
legend({'exact','1st order','2nd order','3rd order'},'Location','southeast');
xlabel('x');
ylabel('Approximations to f(x) = sqrt(x)');

% Calculating True errors (True Error = Exact - Approx)
e1x = fx - f1x;
e2x = fx - f2x;
e3x = fx - f3x;

% Plotting the errors
figure(2)
p = plot(x,e1x,'o-',x,e2x,'^-',x,e3x,'s-',x,zeros(20,1),'-k');
legend([p(1:3)],'E1(x)','E2(x)','E3(x)');
axis([xleft,xright,-0.05,0.05])
xlabel('x');
ylabel('True Error');