如何在Java数组中实现线性插值方法?

5

我正在开发一个简单的线性插值程序。在实现算法时遇到了一些问题。假设有12个数字,我们让用户输入其中3个(位置0、位置6和位置12)。然后程序会计算其他数字。这是我的一段代码:

static double[] interpolate(double a, double b){
    double[] array = new double[6];
    for(int i=0;i<6;i++){
        array[i] = a + (i-0) * (b-a)/6;
    }
    return array;
}

static double[] interpolate2(double a, double b){
    double[] array = new double[13];
    for(int i=6;i<=12;i++){
        array[i] = a + (i-6) * (b-a)/6;
    }
    return array;
}

正如您所看到的,我使用了两个函数。但是我想找一个通用函数来完成这项工作。然而,我不知道如何找到一种通用的方法来表示i-0i-6。怎么解决呢?根据浮点线性插值,我知道也许我应该添加一个形式参数float f。但我不太明白float f是什么意思,以及如何根据它修改我的代码。有谁能帮帮我吗?谢谢。

1个回答

7
如果您想将区间插值到不同数量的数字,只需将输出数字的计数添加到函数参数即可。 例如:
/***
 * Interpolating method
 * @param start start of the interval
 * @param end end of the interval
 * @param count count of output interpolated numbers
 * @return array of interpolated number with specified count
 */
public static double[] interpolate(double start, double end, int count) {
    if (count < 2) {
        throw new IllegalArgumentException("interpolate: illegal count!");
    }
    double[] array = new double[count + 1];
    for (int i = 0; i <= count; ++ i) {
        array[i] = start + i * (end - start) / count;
    }
    return array;
}

那么你只需要调用interpolate(0, 6, 6);或者interpolate(6, 12, 6);或者interpolate(6, 12, 12);或者其他你想要的数字。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接