java 线性插值

引入maven

1
2
3
4
5
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 public static double[] interpolations(double[] x, double[] y, double[] z) {
double[] interV = new double[z.length];
UnivariateInterpolator interpolator = new LinearInterpolator();
//UnivariateInterpolator interpolator = new SplineInterpolator();平滑曲线
UnivariateFunction function = interpolator.interpolate(x, y);
for (int i = 0; i < z.length; i++) {
interV[i] = function.value(z[i]);
}
return interV;
}

public static void main(String[] args) {
//已知下标1,3,5,7,9对应的数值为0.1, 0.5, 2.2, 1.2, 3.1,求下标2, 4, 6, 8对应的数值
double[] x = new double[] {1, 3, 5, 7, 9};
double[] y = new double[] {0.1, 0.5, 2.2, 1.2, 3.1};
double[] z = new double[] {2, 4, 6, 8};
double[] v = interpolations(x, y, z);
System.out.println(Arrays.toString(v));
}

common-math3官方文档