使用 Apache Commons Math 插值函数

Interpolate function using Apache Commons Math

我正在尝试实现一些插值函数来绘制一些值,其中 X 值 = Date.seconds 且 Y 值 = double。

我一直在研究使用 Apache Commons Math 库来实现这一点,并且我找到了一种方法,我认为我可以使用 here

我想了解的方法:

public double linearInterp(double[] x, double[] y, double xi) {
   // return linear interpolation of (x,y) on xi
   LinearInterpolator li = new LinearInterpolator();
   PolynomialSplineFunction psf = li.interpolate(x, y);
   double yi = psf.value(xi);
   return yi;
}

我不明白应该从哪里得到 xi 值?

xi 是什么 我要为 xi 传递给此方法的值是多少,我是否应该遍历我的 X 值数组并传入 X 的第 i 个元素和XY?

当我想绘制这个新数据时,我是否使用返回的 yi 和传入的 xi 来绘制?

interpolate 方法需要成对的数组(此处称为 xy)和 returns 适合这些值的函数 (psf)尽可能的好。

此函数然后用于插入给定 xi 值的 yi 值(通常不包含在用于定义函数的 x/y 数组中)。

所以你有一对包含定义函数的 x 和 y 值,并使用这个函数来插入缺失值。

请参阅 Apache Commons 上的 userguide(第 4.4 章:插值)。


示例:

绿点是已知值对。这些由 xy 值数组定义。

调用interpolate时,返回PolynomialSplineFunctionreturns使用已知值对逼近的函数。函数的形状由使用的 UnivariateInterpolator 类型定义。在问题示例中,使用了 LinearInterpolator。该图显示了样条插值器返回的函数。

红点表示插值函数上具有未知 y 值的值(这将是问题示例中 x 值为 xi 的值)。

如果您需要计算多个额外值,请使用这样的函数

public double[] linearInterp(double[] x, double[] y, double[] xi) {
   LinearInterpolator li = new LinearInterpolator(); // or other interpolator
   PolynomialSplineFunction psf = li.interpolate(x, y);

   double[] yi = new double[xi.length];
   for (int i = 0; i < xi.length; i++) {
       yi[i] = psf.value(xi[i]);
   }
   return yi;
}

一个计算例子:

public class Interpolate {

    public static void main(String[] args) {
        double[] x = { 0, 50, 100 };
        double[] y = { 0, 50, 200 };

        LinearInterpolator interp = new LinearInterpolator();
        PolynomialSplineFunction f = interp.interpolate(x, y);

        System.out.println("Piecewise functions:");
        Arrays.stream(f.getPolynomials()).forEach(System.out::println);

        double value = f.value(70);
        System.out.println("y for xi = 70: " + value);
    }
}

给出三个已知值对:

(0, 0)
(50, 50)
(100, 200)

一个值未知:

(70, ?)

LinearInterpolator 对给定值进行插值并生成具有两个分段线性多项式的函数:

y = x             (for x values < 50)
y = 50 + 3 * x    (for x-values >= 50)

插值后的xi(此处:70)的值为

y = 50 + 3 * (70 - 50) = 110