java 如何在java数组中实现线性插值方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30182467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement linear interpolation method in java array?
提问by turf
I am working on a simple linear interpolation program. And I am having some troubles when implementing the algorithm. Assuming there are 12 numbers as a whole, we'll let user input 3 of them(position 0, position 6 and position 12). Then the program will calculate other numbers. Here is a piece of my code to achieve this:
我正在研究一个简单的线性插值程序。我在实现算法时遇到了一些麻烦。假设总共有 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;
}
As you can see, I used two functions. But I want to find a universal function to do this job. However, I don't know how to find a common way to represent i-0
and i-6
. How to fix it? According to Floating point linear interpolation, I know maybe I should add a formal parameter float f
. But I am not quite understand what does float f
mean and how to modify my code based on it. Could anyone help me? Thank you.
如您所见,我使用了两个函数。但我想找到一个通用功能来完成这项工作。但是,我不知道如何找到表示i-0
和的通用方法i-6
。如何解决?根据浮点线性插值,我知道也许我应该添加一个形参float f
。但我不太明白是什么float f
意思以及如何基于它修改我的代码。有人可以帮助我吗?谢谢你。
回答by Luo
If you want to interpolate intervals to different count of numbers, you can just add the count of output numbers to function parameter. Example:
如果要将区间内插到不同的数字计数,只需将输出数字的计数添加到函数参数即可。例子:
/***
* 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;
}
Then you can just call interpolate(0, 6, 6);
or interpolate(6, 12, 6);
or interpolate(6, 12, 12);
or whatever you want.
然后你可以打电话interpolate(0, 6, 6);
或interpolate(6, 12, 6);
或interpolate(6, 12, 12);
或任何你想要的。