Tur*_*urf 3 java arrays linear-interpolation
我正在研究一个简单的线性插值程序。而且在实现算法时遇到了一些麻烦。假设总共有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;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我使用了两个函数。但是我想找到一个通用的功能来完成这项工作。但是,我不知道如何找到表示i-0和的通用方法i-6。如何解决?根据浮点线性插值,我知道也许我应该添加一个形式参数float f。但是我不太明白这float f意味着什么以及如何基于它修改我的代码。有人可以帮我吗?谢谢。
如果要将间隔插入到不同的数字计数中,则只需将输出数字的计数添加到函数参数中即可。例:
/***
* 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;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以致电interpolate(0, 6, 6);或interpolate(6, 12, 6);或interpolate(6, 12, 12);或任何您想要的电话。
| 归档时间: |
|
| 查看次数: |
11157 次 |
| 最近记录: |