[Solved] How to interpolate through 3 points/numbers with a defined number of samples? (in c#)


This is a generalized solution that works by these principles:

  • Performs linear interpolation
  • It calculates a “floating point index” into the input array
  • This index is used to select 1 (if the fractional parts is very close to 0) or 2 numbers from the input array
  • The integer part of this index is the base input array index
  • The fractional part says how far towards the next array element we should move

This should work with whatever size input arrays and output collections you would need.

public IEnumerable<double> Interpolate(double[] inputs, int count)
{
    double maxCountForIndexCalculation = count - 1;
    for (int index = 0; index < count; index++)
    {
        double floatingIndex = (index / maxCountForIndexCalculation) * (inputs.Length - 1);

        int baseIndex = (int)floatingIndex;
        double fraction = floatingIndex - baseIndex;

        if (Math.Abs(fraction) < 1e-5)
            yield return inputs[baseIndex];
        else
        {
            double delta = inputs[baseIndex + 1] - inputs[baseIndex];
            yield return inputs[baseIndex] + fraction * delta;
        }
    }
}

It produces the two collections of outputs you showed in your question but beyond that, I have not tested it. Little error checking is performed so you should add the necessary bits.

7

solved How to interpolate through 3 points/numbers with a defined number of samples? (in c#)