已知若干插值節點,要求分別用兩點與三點 Lagrange 插值編程實現,並用余項公式估算誤差。
public class Chazhi {
public static void main(String[] args) {
lagrange();
}
public static void lagrange() {
double p = Math.atan(1) * 4; // 即 π
double[] x = { p / 4, p / 3, (5 * p) / 18 };
double[] y = { Math.sqrt(2.0) / 2, Math.sqrt(3.0) / 2 };
double l = 0.0;
for (int j = 0; j < 2; j++) {
double s = 1.0;
for (int i = 0; i < 2; i++) {
if (i != j)
s = s * ((x[2] - x[i]) / (x[j] - x[i]));
}
l = l + s * y[j];
}
double m = (Math.abs(x[0]) / 2)
* Math.abs((x[2] - x[0]) * (x[2] - x[1]));
System.out.println("x=" + x[2]);
System.out.println("L=" + l);
System.out.println("誤差為:" + m);
}
}
代碼結構就是 Lagrange 基函數的兩層循環:外層遍歷每個節點 j 構造對應的基函數 s,內層把除 j 以外的所有因子乘進去,最後累加 s * y[j]。余項則按 |f⁽ⁿ⁾(ξ)|/n! × Π(x−xᵢ) 的形式,用導數上界的粗略估計代入計算。
public class Chazhi {
public static void main(String[] args) {
lagrange_2();
}
public static void lagrange_2() {
double p = Math.atan(1) * 4; // 即 π
double[] x = { p / 6, p / 4, p / 3, (5 * p) / 18 };
double[] y = { 0.5, Math.sqrt(2.0) / 2, Math.sqrt(3.0) / 2 };
double l = 0.0;
for (int j = 0; j < 3; j++) {
double s = 1.0;
for (int i = 0; i < 3; i++) {
if (i != j)
s = s * ((x[3] - x[i]) / (x[j] - x[i]));
}
l = l + s * y[j];
}
double M = (Math.abs(x[0]) / (2 * 3))
* Math.abs((x[3] - x[0]) * (x[3] - x[1]) * (x[3] - x[2]));
System.out.println("x=" + x[3]);
System.out.println("L=" + l);
System.out.println("誤差為:" + M);
}
}
兩個版本的差別只在循環上界與余項公式的階數:點數越多,插值多項式次數越高,理論上在節點附近精度越好,但余項中的導數階數也隨之升高,且高次插值在區間邊緣容易出現龍格現象。因此實戰中並非次數越高越好,分段低次插值(如分段線性、三次樣條)往往更穩定。
本例用 π 的三角函数值作為被插值對象,真值已知,便於直接對比誤差估計與實際誤差的吻合程度,是課堂上常見的驗證方式。