function main
format short
a = -1;
b = 1;
x = (a:0.01:b)';
plot(x, f(x), 'r', 'linewidth', 1);
hold on
xx = (a:2/5:b)';
y = Newton(xx, f(xx));
class(y)
disp("N5 = ")
disp(y)
plot(x, subs(y, x), 'color', '#43A047', 'linewidth', 1);
hold on
xx = (a:2/10:b)';
y = Newton(xx, f(xx));
disp("N10 = ")
disp(y)
plot(x, subs(y, x), 'linewidth', 1);
hold on
xx = (a:2/10:b)';
y = mySpline(xx, f(xx), fff(a), fff(b));
disp("S10 = ")
disp(y)
for i = 1 : 10
l = xx(i);
r = l + 2/10;
x = l:0.01:r;
plot(x, subs(y(i), x), 'b', 'linewidth', 1)
hold on
end
legend(["f(x)" "N5" "N10" "S10"]);
set(gca, 'FontName', 'Times New Roman', 'FontSize', 16);
end
function y = f(x)
y = 1 ./ (1 + 25 * x .* x);
end
function y = fff(x)
y = 50 * (75*x.*x-1) ./ (1+25*x.*x)^3;
end
function N = Newton(a, b)
[n, ~] = size(a);
diff = zeros(n, n);
diff(1, :) = b';
syms x
now = 1;
N = diff(1, 1);
for i = 2 : n
for j = i : n
diff(i, j) = (diff(i-1, j)-diff(i-1, j-1)) / (a(j) - a(j-i+1));
end
now = now * (x-a(i-1));
N = N + diff(i, i) * now;
end
N = expand(N);
N = vpa(N, 5);
end
function S = mySpline(a, b, M1, Mn)
[n, ~] = size(a);
h = a(2:n) - a(1:n-1);
mu = h(1:n-2) ./ (h(1:n-2) + h(2:n-1));
la = 1 - mu;
h1 = h(1:n-2);
h2 = h(2:n-1);
d = 6*((b(3:n)-b(2:n-1))./h2-(b(2:n-1)-b(1:n-2))./h1)./(h1+h2);
A = zeros(n-2, n-2);
for i = 1 : n-2
if (i > 1)
A(i, i-1) = mu(i);
end
A(i, i) = 2;
if (i < n-2)
A(i, i+1) = la(i);
end
end
d(1) = d(1) - mu(1) * M1;
d(n-2) = d(n-2) - la(n-2) * Mn;
M = [M1; chase(A, d)'; Mn];
syms x
x1 = a(2:n) - x;
x2 = x - a(1:n-1);
m1 = M(1:n-1);
m2 = M(2:n);
y1 = b(1:n-1);
y2 = b(2:n);
S = (x1.^3).*m1./(6*h)+(x2.^3).*m2./(6*h)+(y1-h.^2.*m1/6).*x1./h+(y2-h.^2.*m2/6).*x2./h;
S = expand(S);
S = vpa(S, 5);
end
function x = chase(A, d)
[n, ~] = size(A);
u = zeros(n, 1);
l = zeros(n, 1);
y = zeros(n, 1);
u(1) = A(1, 1);
y(1) = d(1);
for i = 2 : n
l(i) = A(i, i-1) / u(i-1);
u(i) = A(i, i) - l(i) * A(i-1, i);
y(i) = d(i) - l(i) * y(i-1);
end
x(n) = y(n) / u(n);
for i = n-1 : -1 : 1
x(i) = (y(i) - A(i, i+1) * x(i+1)) / u(i);
end
end