歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java實現lagrange 插值法

Java實現lagrange 插值法

日期:2017/3/1 9:58:06   编辑:Linux編程

一、題目:已知

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);
}
}

Copyright © Linux教程網 All Rights Reserved