mathnet / mathnet-numerics

Math.NET Numerics
http://numerics.mathdotnet.com
MIT License
3.51k stars 896 forks source link

Error with Linear Interpolation #921

Open aboudoux opened 2 years ago

aboudoux commented 2 years ago

Hello,

I have noticed a bug in Interpolate.Linear Here a unit test to reproduce

[Fact(DisplayName = "Interpolation NAN error")]
    public void Test42()
    {
        var interpolation = Interpolate.Linear(new[] { 40.0, 40.0 }, new[] { 0.57, 0.57 });
        interpolation.Interpolate(40).Should().Be(0.57);
    }

Expected interpolation.Interpolate(40) to be 0.57, but found NaN.

The function works fine in a pyhton script, but not in a C# app :(

jkalias commented 2 years ago

This is quite an edge case. What do you expect for example to happen here, where you have multiple ordinate values for the same abscissa?

var interpolation = Interpolate.Linear(new[] { 40.0, 40.0 }, new[] { 0.57, 0.67 });
interpolation.Interpolate(40); // what to return here??
aboudoux commented 2 years ago

The expected return value in your exemple should be 0.62

Here a "correct" implementation :

public static double LinearInterpolation(double x, double x0, double x1, double y0, double y1)
{
    if ((x1 - x0) == 0)
        return (y0 + y1) / 2;
    return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
}
jkalias commented 2 years ago

I am not sure if this is the correct mathematical behavior to be honest.

Since the function is not one-to-one how can one choose whether to return y0, y1, or any value in between?

I would be curious to hear what people with a math background have to say (@cdrnet? @phihub?)

jkalias commented 2 years ago

Is this still an active issue? If not, can we please close it?