Browse Source

RootFinding: protect newton-raphson better against singularities, more tests

v2
Christoph Ruegg 14 years ago
parent
commit
ccf89f8186
  1. 4
      src/Numerics/RootFinding/Algorithms/HybridNewtonRaphson.cs
  2. 7
      src/UnitTests/RootFindingTests/NewtonRaphsonTest.cs

4
src/Numerics/RootFinding/Algorithms/HybridNewtonRaphson.cs

@ -129,7 +129,7 @@ namespace MathNet.Numerics.RootFinding.Algorithms
continue; continue;
} }
if (Math.Abs(step) < accuracy) if (Math.Abs(step) < accuracy && Math.Abs(fx) < accuracy)
{ {
return true; return true;
} }
@ -149,7 +149,7 @@ namespace MathNet.Numerics.RootFinding.Algorithms
lowerBound = root; lowerBound = root;
fmin = fx; fmin = fx;
} }
else if (Math.Sign(fmin) != Math.Sign(fmax)) else if (Math.Sign(fmin) != Math.Sign(fmax) && Math.Abs(fx) < accuracy)
{ {
return true; return true;
} }

7
src/UnitTests/RootFindingTests/NewtonRaphsonTest.cs

@ -91,6 +91,13 @@ namespace MathNet.Numerics.UnitTests.RootFindingTests
Assert.AreEqual(Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f3, df3, 1, 1.99, 1e-14, 100, 20)); Assert.AreEqual(Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f3, df3, 1, 1.99, 1e-14, 100, 20));
Assert.AreEqual(Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f3, df3, -1.5, 1.99, 1e-14, 100, 20)); Assert.AreEqual(Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f3, df3, -1.5, 1.99, 1e-14, 100, 20));
Assert.AreEqual(Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f3, df3, 1, 6, 1e-14, 100, 20)); Assert.AreEqual(Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f3, df3, 1, 6, 1e-14, 100, 20));
Func<double, double> f4 = x => 1/(2 - x) - x + 6;
Func<double, double> df4 = x => 1/(x*x - 4*x + 4) - 1;
Assert.AreEqual(4 + Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f4, df4, 5, 6, 1e-14, 100, 20), 1e-14);
Assert.AreEqual(4 - Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f4, df4, 2.01, 3, 1e-14, 100, 20));
Assert.AreEqual(4 - Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f4, df4, 2.01, 5, 1e-14, 100, 20));
Assert.AreEqual(4 - Math.Sqrt(3), HybridNewtonRaphson.FindRoot(f4, df4, -2, 4, 1e-14, 100, 20));
} }
[Test] [Test]

Loading…
Cancel
Save