使用 Apache 数学使用样条函数调整 1D 数组大小 - 如何?



我正在寻找一个使用样条函数和 Apache Commons - Math 调整 1D 数组大小的示例。

我需要的是一种扩展和/或缩小输入数组的方法(double[](。

我找不到一个尝试在线搜索的好例子。

这里的诀窍是你需要两个arrays来创建spline,但你只有一个。因此,您需要制造一个array。您可以假设输入array包含您的y值,并且新的制造数组包含您的x值,因此对于任何给定x您都有相应的y

免责声明,我还没有测试过这段代码,所以一定要相应地调整。

// To expand the array
public static double[] expand(double[] array, int newSize) {
final int length = array.length;
// let's calculate the new step size
double step = (double) length / (newSize + 1);
// fabricated array of x values
double[] x = new double[length];
for(int i = 0; i < length; ++i) {
x[i] = i;
}
// using Linear interpolator but it can be any other interpolator
LinearInterpolator li = new LinearInterpolator(); // or other interpolator
PolynomialSplineFunction psf = li.interpolate(x, array);
double[] expandedArray = new double[newSize];
double xi = x[0];
for (int i = 0; i < newSize - 1; ++i) {
expandedArray[i] = psf.value(xi);
xi += step;
}
expandedArray[newSize - 1] = array[length - 1];
return expandedArray;
}

shrink数组,您可以decimate输入array即只需创建一个新的较小array并根据新的步长获取值,或者像以前一样使用interpolator

// To shrink the array
public static double[] shrink(double[] array, int newSize) {
final int length = array.length;
// let's calculate the new step size
double step = (double) length / (newSize - 1);
// fabricated array of x values
double[] x = new double[length];
for(int i = 0; i < length; ++i) {
x[i] = i;
}
// using Linear interpolator but it can be any other interpolator
LinearInterpolator li = new LinearInterpolator(); // or other interpolator
PolynomialSplineFunction psf = li.interpolate(x, array);
double[] expandedArray = new double[newSize];
double xi = x[0];
for (int i = 0; i < newSize - 1; ++i) {
expandedArray[i] = psf.value(xi);
xi += step;
}
expandedArray[newSize - 1] = array[length - 1];
return expandedArray;
}

最新更新