Skip to content

Commit 114f0ef

Browse files
committed
Root Finding: Newton-Raphson to check for zero after each eval to avoid NaN. Closes #774.
1 parent b36d0f4 commit 114f0ef

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

src/Numerics/RootFinding/NewtonRaphson.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,11 @@ public static bool TryFindRoot(Func<double, double> f, Func<double, double> df,
9999
{
100100
// Evaluation
101101
double fx = f(root);
102+
if (fx == 0.0)
103+
{
104+
return true;
105+
}
106+
102107
double dfx = df(root);
103108

104109
// Netwon-Raphson step

src/Numerics/RootFinding/RobustNewtonRaphson.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,11 @@ public static bool TryFindRoot(Func<double, double> f, Func<double, double> df,
9191

9292
root = 0.5*(lowerBound + upperBound);
9393
double fx = f(root);
94+
if (fx == 0.0)
95+
{
96+
return true;
97+
}
98+
9499
double lastStep = Math.Abs(upperBound - lowerBound);
95100
for (int i = 0; i < maxIterations; i++)
96101
{
@@ -119,6 +124,11 @@ public static bool TryFindRoot(Func<double, double> f, Func<double, double> df,
119124
// Bisection
120125
root = 0.5*(upperBound + lowerBound);
121126
fx = f(root);
127+
if (fx == 0.0)
128+
{
129+
return true;
130+
}
131+
122132
lastStep = 0.5*Math.Abs(upperBound - lowerBound);
123133
if (Math.Sign(fx) == Math.Sign(fmin))
124134
{
@@ -146,6 +156,11 @@ public static bool TryFindRoot(Func<double, double> f, Func<double, double> df,
146156

147157
// Evaluation
148158
fx = f(root);
159+
if (fx == 0.0)
160+
{
161+
return true;
162+
}
163+
149164
lastStep = step;
150165

151166
// Update bounds

0 commit comments

Comments
 (0)