diff --git a/src/Numerics.Tests/InterpolationTests/LinearSplineTest.cs b/src/Numerics.Tests/InterpolationTests/LinearSplineTest.cs index 79980ee31..ae0105678 100644 --- a/src/Numerics.Tests/InterpolationTests/LinearSplineTest.cs +++ b/src/Numerics.Tests/InterpolationTests/LinearSplineTest.cs @@ -29,6 +29,7 @@ using MathNet.Numerics.Interpolation; using NUnit.Framework; +using System; namespace MathNet.Numerics.Tests.InterpolationTests { @@ -138,5 +139,17 @@ public void FewSamples() Assert.That(() => LinearSpline.Interpolate(new double[1], new double[1]), Throws.ArgumentException); Assert.That(LinearSpline.Interpolate(new[] { 1.0, 2.0 }, new[] { 2.0, 2.0 }).Interpolate(1.0), Is.EqualTo(2.0)); } + + [Test] + public void DoNotExtrapolate() + { + LinearSpline ip = LinearSpline.Interpolate(_t, _y); + + Assert.Throws(() => ip.Interpolate(-2.1, false)); + Assert.Throws(() => ip.Interpolate(10.0, false)); + + Assert.Throws(() => LinearSpline.Interpolate(new[] { 1.0, 2.0 }, new[] { 2.0, 2.0 }).Interpolate(0.9, false)); + Assert.Throws(() => LinearSpline.Interpolate(new[] { 1.0, 2.0 }, new[] { 2.0, 2.0 }).Interpolate(3.0, false)); + } } } diff --git a/src/Numerics/Interpolation/LinearSpline.cs b/src/Numerics/Interpolation/LinearSpline.cs index 0f192c3e3..8c127df60 100644 --- a/src/Numerics/Interpolation/LinearSpline.cs +++ b/src/Numerics/Interpolation/LinearSpline.cs @@ -130,6 +130,24 @@ public static LinearSpline Interpolate(IEnumerable x, IEnumerableInterpolated value x(t). public double Interpolate(double t) { + return Interpolate(t, true); + } + + /// + /// Interpolate at point t. + /// + /// Point t to interpolate at. + /// set to fals if extrapolate should not be allowed + /// Interpolated value x(t). + /// Thrown when t is outside range and would result in Extrapolation! + public double Interpolate(double t, bool allowExtrapolate) + { + if (!allowExtrapolate && + (t < _x[0] || t > _x[_x.Length - 1])) + { + throw new ArgumentOutOfRangeException("'t' is outside of the constructed array. This would result in Extrapolation!"); + } + int k = LeftSegmentIndex(t); return _c0[k] + (t - _x[k])*_c1[k]; }