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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With