I have piecewise linear function
I try to build a polynomial of Lagrange for 2, 6, 14 hosts. But for my hosts, my original function become not correct:
I think that my polynomial turns right, but I have troubles to count and build measure of inaccuracy
a = 1;
b = -1;
c = -1;
d = 1;
x = -1:0.33:1;
y = [];
for i = 1 : length(x)
if (x(i) <= c/2)
y(i) = x(i)+ 1;
elseif(x(i) >= d/2)
y(i) = x(i) - 1;
else
y(i) = -x(i);
end
end
plot(x, y);
hold on
nx = -1:0.01:1;
ny=lagrange(x,y,nx);
plot(x,y,'bo');
plot(nx,ny,'r');
function ny=lagrange(x,y,nx)
N = length(x);
ny=zeros(size(nx));
for k=1:N
t=ones(size(nx));
for j=[1:k-1, k+1:N]
t=t.*(nx-x(j))/(x(k)-x(j));
end
ny = ny + y(k)*t;
end
Well, I made some mistakes. First of all, I passed on wrong parameters to function. Also, I didn't correctly calculate the values of the original function. The "original" func calculate the values of original graph. The "lagrange" func calculate the values polynomial.
x = -1:0.01:1;
y = [];
y = original(x);
subplot (2, 1, 1);
plot(x, y);
xlabel('x');
ylabel('y');
hold on;
grid on;
%hosts
xx = -1:0.5:1;
%values of original func in hosts
yy = original(xx);
plot(xx,yy,'o');
nx = -1:0.01:1;
ny=lagrange(xx,yy,nx);
plot(nx,ny,'r');
subplot (2, 1, 2);
%measure of inaccuracy
plot(x,ny-y, '');
grid on;