How to implement linear interpolation method in java array? -
i working on simple linear interpolation program. , having troubles when implementing algorithm. assuming there 12 numbers whole, we'll let user input 3 of them(position 0, position 6 , position 12). program calculate other numbers. here piece of code achieve this:
static double[] interpolate(double a, double b){ double[] array = new double[6]; for(int i=0;i<6;i++){ array[i] = + (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] = + (i-6) * (b-a)/6; } return array; }
as can see, used 2 functions. want find universal function job. however, don't know how find common way represent i-0
, i-6
. how fix it? according floating point linear interpolation, know maybe should add formal parameter float f
. not quite understand float f
mean , how modify code based on it. me? thank you.
if want interpolate intervals different count of numbers, can add count of output numbers function parameter. example:
/*** * interpolating method * @param start start of interval * @param end end of interval * @param count count of output interpolated numbers * @return array of interpolated number 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]; (int = 0; <= count; ++ i) { array[i] = start + * (end - start) / count; } return array; }
then can call interpolate(0, 6, 6);
or interpolate(6, 12, 6);
or interpolate(6, 12, 12);
or whatever want.
Comments
Post a Comment