%Program that approximates the function f(x)=x^2 about x=0 by a 1st order, 2nd
%order, and a 3rd order Taylor approximation.  Written by Philip Shaw,
%Fordham University, 2018.
clear all
h=-1:.00001:1; %create the space for h values
xbar=0; %point which we are approximating around
tic %start a timer 

fxx=(xbar+h).^2; %true function value
fxhn1=xbar^2+2*xbar.*h; %first-order approximation
fxhn2=xbar^2+2*xbar.*h+2*h.^2./2; %second-order approximation
fxhn3=xbar^2+2*xbar.*h+2*h.^2./2; %third-order approximation
tloop=toc %stop the timer and store the result

plot(h,fxx,h,fxhn1,h,fxhn2,h,fxhn3,'linewidth',2)
legend('x^2','f(x+h) n=1','f(x+h) n=2','f(x+h) n=3')
title('Taylor Approximation of f(x)=x^2 About x=0')
xlabel('h')
ylabel('f(1+h)')
display('Average Absolute Deviation of 1st Order Approx')
mean(abs(fxx-fxhn1))
display('Average Absolute Deviation of 2nd Order Approx')
mean(abs(fxx-fxhn2))
display('Average Absolute Deviation of 3rd Order Approx')
mean(abs(fxx-fxhn3))