Question

# % This program calculates the Lagrange interpolating polynomial of a given % xp and returns the...

% This program calculates the Lagrange interpolating polynomial of a given % xp and returns the value
clc, clear all;
format short;
x=[0 20 40 60 80 100];% This string can be filled by Matlab
f_x=[26.0 48.6 61.6 71.2 74.8 75.2]; % You can create a separate function to fill
f_x automatically
n=length(x)-1;
xp=input('Enter a value xp between 0 and 100: '); P_x=0;
for i=1:n+1
L_k=1;
for j=1:n+1
if j~=i L_k=L_k*(xp-x(j))/(x(i)-x(j));
end end
P_x=P_x+f_x(i)*L_k;
end
disp ('The polynomial P_xp at xp=55 is: '); P_xp=P_x

_______

given function f(x)=cos(x)-x
A. Edit the program in such a way it:

1. Prompts the user to enter a string containing the values of x (x0, x1,
x2,...xn).

2. Calculates the values of f(x) that should be filled in the string called f_x. 3. Returns the value of the P3(x1) (Third order Lagrange InterpolatingPolynomial evaluated at x=x1).

B. Compare the P3(x1) returned by the program to the f(x1) available inside
the string f_x.

We have modified the the given code in the required form.

OUTPUT

-------------------------------------------MATLAB code-------------------------------------------

clc;
clear all
format short;
fprintf('\n\n')
x=input('Enter the values of x as a vector: ');
f_x=cos(x)-x;
n=numel(x)-1;

% xp=input('Enter a value xp between 0 and 100: ');

xp=x(2);
P_x=0;

for i=1:n+1
L_k=1;
for j=1:n+1
if j~=i
L_k=L_k*(xp-x(j))/(x(i)-x(j));
end
end
P_x=P_x+f_x(i)*L_k;
end
fprintf('\n\n')
disp (['The polynomial P_xp at x1=',num2str(x(2)), ' is: ', num2str(P_x)]);
fprintf('\n\n')
disp (['Absolute error at x1=',num2str(x(2)), ' is: ', num2str(abs(P_x-f_x(2)))]);
fprintf('\n\n')

#### Earn Coins

Coins can be redeemed for fabulous gifts.