我在使用分段立方Hermite多项式的代码时遇到问题。在我的作业中,我们不允许使用pchip
。我们应该编写一个函数,它将输入参数作为整数n和3乘n矩阵,其中包含x值,在每个x处计算的函数值,以及在此处计算的导数值。每个x;分别在矩阵的第一,第二和第三行。
利用这些信息,我们应该在输入矩阵的第一行给出的间隔的每个子区间上计算每个Hermite多项式的系数,然后使用mkpp
将其完全分割。
不幸的是,我的代码产生了一个非常差的插值多项式,我无法弄清楚为什么。例如,对于函数x^2
,我们有例如n = 4
和M = [0,1,2,3; 0,1,4,9; 0,1,4,6]
,当插入我的函数时会生成以下图表
我真的很感激这方面的帮助,它让我疯狂。
这是我的代码:
function [ HP ] = HermiteInter( n,M )
%HermiteInter
% This function constructs a peicewise cubic Hermite polynomial.
% The input areguments are an integer n and M a 3 by n matrix, whose
% first row contains the values of x which a given function will be
% evaluated at. The second row contains the values of a function
% evaluated at those
% points and the third row contains the value of the derivative of
% the function evaluated at those points.
% Divided differences using these values are found by calling the
% function HermiteDD. These divided differences are then passed into the
% function mkpp to create the peicewise polynomial.
X = M(1,:);
Y = M(2,:);
Z = M(3,:);
Q = zeros(n-1,4);
for i = 1 : n-1
Q(i,:) = HermiteDD([X(i),X(i),X(i+1),X(i+1)],[Y(i),Y(i+1)],[Z(i),Z(i+1)]);
end
HP = mkpp(X,Q);
end
function [ HDD ] = HermiteDD(X,Y,Z)
%HermiteDD
% This function creates a table of divided differences for
% Hermite polynomials. The input arguments are X, the values at
% which a function was evaluated at, Y the values of the function at
% these points and Z the values of the derivative of the function at
% these points.
DD = zeros(4, 4);
DD(1, 1) = Y(1);
DD(2, 1) = Y(1);
DD(3, 1) = Y(2);
DD(4, 1) = Y(2);
DD(1, 2) = Z(1);
DD(2, 2) = (Y(1)-Y(2))/(X(1)-X(3));
DD(3, 2) = Z(2);
for j = 3 : 4
for i = 1 : (4 - j+1)
DD(i,j) = (DD(i + 1, j - 1) - DD(i, j - 1)) / (X(i + j-1) - X(i));
end
end
HDD = DD(1,:);
end