Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

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

So for example we have 1, 5, and 10 and we want to interpolate between these with 12 points, we should get:

1.0000        
1.7273   
2.4545    
3.1818   
3.9091    
4.6364   
5.4545   
6.3636   
7.2727  
8.1818    
9.0909    
10.0000   

say we have 5, 10, and 4 and again 12 points, we should get:

5.0000
5.9091
6.8182
7.7273
8.6364
9.5455
9.4545
8.3636
7.2727
6.1818
5.0909
4.0000
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...