2015-05-12 1567 views
2

我正在研究一個簡單的線性插值程序。在執行算法時我遇到了一些麻煩。假設總共有12個數字,我們將讓用戶輸入3個數字(位置0,位置6和位置12)。然後該程序將計算其他數字。下面是一段我的代碼來實現這一目標:如何在java數組中實現線性插值方法?

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的常用方法。如何解決它?根據Floating point linear interpolation,我知道也許我應該添加一個正式參數float f。但我不太明白float f是什麼意思,以及如何根據它來修改我的代碼。任何人都可以幫我嗎?謝謝。

回答

4

如果要將間隔內插到不同數量的計數中,可以將輸出數量的計數添加到函數參數中。 例子:

/*** 
* 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);或。

+1

謝謝!!!!!! – Turf