java拉格朗日插值法实现拉格朗日多项式
时间: 2023-05-30 22:04:06 浏览: 230
以下是Java代码实现拉格朗日插值法:
```
public class LagrangeInterpolation {
public static double interpolate(double[] x, double[] y, double xi) {
if (x.length != y.length) {
throw new IllegalArgumentException("x and y must have the same size");
}
double result = 0;
for (int i = 0; i < x.length; i++) {
double term = y[i];
for (int j = 0; j < x.length; j++) {
if (i != j) {
term *= (xi - x[j]) / (x[i] - x[j]);
}
}
result += term;
}
return result;
}
}
```
其中,`interpolate`方法接受三个参数:`x`表示已知点的x坐标数组,`y`表示已知点的y坐标数组,`xi`表示要求解的插值点的x坐标。
该方法首先检查`x`和`y`数组的长度是否相等,如果不相等则抛出异常。然后,对每个已知点,计算该点对应的拉格朗日基函数的值,并将其乘以该点的y值,最后将所有基函数的值相加得到插值结果。
以下是使用示例:
```
double[] x = {0, 1, 2, 3};
double[] y = {1, 3, 5, 7};
double xi = 1.5;
double yi = LagrangeInterpolation.interpolate(x, y, xi);
System.out.println(yi); // Output: 4.0
```
该示例中,已知四个点(0,1)、(1,3)、(2,5)、(3,7),要求在x=1.5处插值。调用`interpolate`方法,得到插值结果4.0。