Skip to content

Commit 4c65b58

Browse files
committed
Improved root finding to avoid over/underflow.
1 parent de9e9ee commit 4c65b58

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/Numerics.Tests/RootFindingTests/RobustNewtonRaphsonTest.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,24 @@ public void InfinitelyManyRootsWithGivenAccuracy()
133133
Assert.AreEqual(-50, RobustNewtonRaphson.FindRoot(f1, df1, -200, 100, 1e-8), 1e-6);
134134
}
135135

136+
[Test]
137+
public void BoundsNearMaxValueNoOverflow()
138+
{
139+
// degenerate case with infinitely many roots
140+
Func<double, double> f1 = x => 0.0;
141+
Func<double, double> df1 = x => 0.0;
142+
Assert.AreEqual(double.MaxValue, RobustNewtonRaphson.FindRoot(f1, df1, double.MaxValue - 2, double.MaxValue - 1), 1e-6);
143+
}
144+
145+
[Test]
146+
public void BoundsNearMinValueNoUnderflow()
147+
{
148+
// degenerate case with infinitely many roots
149+
Func<double, double> f1 = x => 0.0;
150+
Func<double, double> df1 = x => 0.0;
151+
Assert.AreEqual(double.MinValue, RobustNewtonRaphson.FindRoot(f1, df1, double.MinValue + 1, double.MinValue + 2), 1e-6);
152+
}
153+
136154
[Test]
137155
public void NoRoot()
138156
{

src/Numerics/RootFinding/RobustNewtonRaphson.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ public static bool TryFindRoot(Func<double, double> f, Func<double, double> df,
7777
double fmin = f(lowerBound);
7878
double fmax = f(upperBound);
7979

80-
root = 0.5 * (lowerBound + upperBound);
80+
root = lowerBound + 0.5 * (upperBound - lowerBound);
8181
double fx = f(root);
8282
if (Math.Abs(fx) < accuracy)
8383
{

0 commit comments

Comments
 (0)