一、题目:已知
1、请用两点 Lagrange插值 编程实现 ,用余项公式求误差;
1.1)程序源代码
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);
}
}
1.2)程序结果:
2、请用三点 lagrange 插值 编程实现,用余项公式求误差;
2.1)程序源代码:
public class Chazhi {
public static void main(String[] args) {
// lagrange();
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);
}
}