簡介
wikipedia: Neville's method
在數學上,Neville 算法是一種計算插值多項式方法,由數學家Eric Harold Neville提出。由給定的n+1個節點,存在一個唯一的冪次≤n的多項式存在,並且通過給定點。
算法
給定n+1個節點及其對應函數值 \((x_i, y_i)\),假設 \(P_{i,j}\) 表示 \(j-i\) 階多項式,並且滿足通過節點 \((x_k, y_k) \quad k =i, i+1, \cdots, j\)。\(P_{i,j}\) 滿足以下迭代關系
\[\begin{eqnarray} \begin{aligned} & p_{i,i}(x) = y_i \cr & P_{i,j}(x) = \frac{(x_j - x)p_{i,j-1}(x) + (x - x_i)p_{i+1,j}(x)}{x_j - x_i}, \quad 0\le i\le j \le n \end{aligned} \end{eqnarray}\]
以n=4的節點舉例,其迭代過程為
\[\begin{eqnarray} \begin{aligned} & p_{1,1}(x) = y_1, \cr & p_{2,2}(x) = y_2, p_{1,2}(x), \cr & p_{3,3}(x) = y_3, p_{2,3}(x), p_{1,3}(x),\cr & p_{4,4}(x) = y_4, p_{3,4}(x), p_{2,4}(x), p_{1,4}(x)\cr \end{aligned} \end{eqnarray}\]
代碼
偽代碼
- 由於計算插值點為一向量,為避免過多層循環嵌套,將每個 \(P_{i,j}\) 都改寫為向量形式,各元素分別儲存多項式在插值點 \(x_0\) 處函數值。
- 只有每次當一列 \(P_{i,j}\) 計算完后,才能利用迭代公式計算下一列 \(P_{i,j}\) 多項式,因此外層循環為計算每列 \(P_{i,j}\) 多項式。
- 每列 \(P_{i,j}\) 個數是逐漸減少的,最開始有n個多項式,最終循環只有一個。
可將矩陣P[nRow,nCol]用於存儲多項式 \(P_{i,j}(x)\)。其中每行為 \(P_{i,j}(x_k)\) 在 nCol 個插值點\(x_k\)處函數值。每次外層循環 \(P_{i,j}(x)\) 個數減少,此時從最后一行開始舍棄,每次只循環
for irow = 1: (nRow - icol) %
\(x_i\)與\(x_j\)分別用變量x1與x2代替。迭代公式可表示為
for icol = 1:nRow - 1
for irow = 1: (nRow - icol) %
x1 = nodes(irow); x2 = nodes(irow + icol);
P(irow, :) = ( (x2 - x0).*P(irow, :) + (x0 - x1 ).*P(irow+1, :) )./( x2 - x1 );
end% for
end% for
最終完整代碼為
function evalPol = f1300000_Neville(x0, nodes, fnodes)
% Implement Neville's algorithm to evaluate interpolation polynomial at x0
% Input:
% x0 - the point where we want to evaluate the polynomial
% nodes - vector containing the interpolation nodes
% fnodes - vector containing the values of the function
% Output:
% evalPol - vector containing the value at x0 of the different
% the interpolating polynomials
if iscolumn(x0)
x0 = x0'; % transfer to row vector
end
if isrow(fnodes)
fnodes = fnodes';
end
nCol = length(x0);
nRow = length(nodes);
% P = zeros(nRow, nCol);
P = repmat(fnodes, 1, nCol);
for icol = 1:nRow - 1
for irow = 1: (nRow - icol) %
x1 = nodes(irow); x2 = nodes(irow + icol);
P(irow, :) = ( (x2 - x0).*P(irow, :) + (x0 - x1 ).*P(irow+1, :) )./( x2 - x1 );
end% for
end% for
evalPol = P(1,:);
end
