please provide a valid code. Thanks! Let f(z) = cos(z). One way to approximate a
ID: 3210100 • Letter: P
Question
please provide a valid code. Thanks!
Let f(z) = cos(z). One way to approximate a derivative is to construct a polynomial interpo- a) Using your code from above, write a MATLAB function that constructs an approximate b) Use (a) to approximate f'(0.5) by using polynomials of degree d = { 2, 3, 4, 10). Com- c) Compare the pattern in part (b) of question 4 to the pattern in part (b) of this question. lation and evaluate the derivative of the interpolation derivative of f(x) at 0.5 by using polynomials of degree d. pute the relative error for each estimationExplanation / Answer
a)
function y0 = lagrange_interp(x, y, z,m)
% m is number of points
% x is the vector of abscissas.
% y is the matching vector of ordinates.
% z represents the target to be interpolated
% y0 represents the solution from the Lagrange interpolation
y0 = 0;
%n = length(x);
for j = 1 : m
t = 1;
for i = 1 : m
if i~=j
t = t * (z-x(i))/(x(j)-x(i));
end
end
y0 = y0 + t*y(j);
end
p=y0;
end
b)
function dummy = lagrang11( )
clc;
clear all;
format long
for j=1:9
d=j+1; % d={2,3,..10}
h=1/d; % step size
x=0:h:d; % x values
for i=1:d+1
y(i)=-sin(x(i)); % y function or derivative of f(x)
end
z=0.5; % given point
d
y0 = lagrange_interp(x, y, z,d+1) % calling the function
end
function y0 = lagrange_interp(x, y, z,m)
% m is number of points
% x is the vector of abscissas.
% y is the matching vector of ordinates.
% z represents the target to be interpolated
% y0 represents the solution from the Lagrange interpolation
y0 = 0;
%n = length(x);
for j = 1 : m
t = 1;
for i = 1 : m
if i~=j
t = t * (z-x(i))/(x(j)-x(i));
end
end
y0 = y0 + t*y(j);
end
p=y0;
end
end
%%% solution %%%%'
d =
2
y0 =
-0.479425538604203
d =
3
y0 =
-0.479288094624069
d =
4
y0 =
-0.479425538604203
d =
5
y0 =
-0.479425389717234
d =
6
y0 =
-0.479425538604203
d =
7
y0 =
-0.479425538515796
d =
8
y0 =
-0.479425538604203
d =
9
y0 =
-0.479425538604170
d =
10
y0 =
-0.479425538604203
>>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.