%% Example for Taylor's theorem
% This is an example for an mlx file.
% All Matlab assignments have to be done in this format.
% Use text fields for stating problems, explanations, observations, answers to questions. Do NOT use % code comments for this
% Use % code comments only for explaining what a line of code does

clearvars      % start all mlx files with this (clears existing values of variables)
format long g  % show output with 15 digits

% This is Example 1 from the Review of Taylor's theorem.
% make sure you understand the code below
% try changing the line d=0.02 to e.g. d=0.03 and rerun the code (F4 on PC, Option-Command-R on Mac)
% We consider the function f(x)=x^{-1}.
% We want to approximate f(2.02)=\frac1{2.02} using a Taylor polynomial about x_0=2.
% The Taylor polynomial p_n(x) is defined as
%        p_n(x) = f(x_0) + f'(x_0)(x-x_0)+\cdots + f^{(n)}(x_0)
% \frac{(x-x_0)^n}{n!}
% We have f(x)=p_n(x)+R_{n+1} with the remainder term
%        R_{n+1} = f^{(n+1)}(t) \frac{(x-x_0)^{n+1}}{(n+1)!}
% where t is between x and x_0.
%% Taylor polynomial p_1(x)
% We obtain
%       p_1(x)=f(x_0)+f'(x_0)(x-x_0) = \frac12-\frac14(x-2)
% Evaluating this for x=2.02 gives
%      \tilde y = \frac12-\frac14\cdot 0.02

d = 0.02;        % d=x-x0   <===== change this line and rerun the code!
yt = 1/2-1/4*d

% Find remainder term R_2
%      R_2 = f''(t) \frac{(x-x_0)^2}{2!} = 2\cdot t^{-3} \cdot \frac{(x-x_0)^2}{2}
% = t^{-3} \cdot (x-x_0)^2
% where t is between x=2.02 and x_0=2. Hence we obtain|t^{-3}| \le 2^{-3} and the upper bound
%      |R_2| \le  2^{-3} \cdot(x-x_0)^2
%

R2bound = 2^-3*d^2

% Find the actual error |y-\tilde y|

y = (2+d)^-1;         % exact value
error = abs(y-yt)

% Note:
% error \le R2bound
% error is close to R2bound
%% Taylor polynomial p_3(x)
% We obtain
%       p_3(x)=f(x_0)+\cdots +f^{(3)}(x_0)\frac{(x-x_0)^3}{3!}
% = \frac12-\frac14(x-2)+ \frac18(x-2)^2-\frac1{16}(x-2)^3
% Evaluating this for x=2.02 gives
%      \tilde y = \frac12-\frac14\cdot 0.02
% +\frac18 0.02^2-\frac1{16}0.02^3

yt = 1/2-1/4*d+1/8*d^2-1/16*d^3

% Find remainder term R_4
%      R_4 = f^{(4)}(t) \frac{(x-x_0)^4}{4!} = 24\cdot t^{-5} \cdot \frac{(x-x_0)^4}{24} = t^{-5}\cdot (x-x_0)^4
% where t is between x=2.02 and x_0=2. Hence we obtain |t^{-5}| \le 2^{-5} and the upper bound
%      |R_2| \le
%     2^{-5} \cdot (x-x_0)^4

R4bound = 2^-5*d^4

% Find the actual error |y-\tilde y|

y = (2+d)^-1;         % exact value
error = abs(y-yt)

% Note:
% error \le R4bound
% error is close to R4bound