From c89add108f5b6bf7f3baf7c1ebdf7d7bd6fa3f00 Mon Sep 17 00:00:00 2001
From: Oleg Alexandrov <oleg.alexandrov@gmail.com>
Date: Thu, 14 Apr 2022 10:44:15 -0700
Subject: [PATCH] Brent root fix (#362)

* Bugfix for brent_root: It could fail to identify the bracket correctly

* Refine the bugfix per Wikipedia, and fix the test
---
 src/Utilities.cpp  | 6 ++++++
 tests/SarTests.cpp | 4 ++--
 2 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/src/Utilities.cpp b/src/Utilities.cpp
index 6b448b9..5ec9cb0 100644
--- a/src/Utilities.cpp
+++ b/src/Utilities.cpp
@@ -296,6 +296,12 @@ double brentRoot(double lowerBound, double upperBound,
     previousPoint = currentPoint;
     previousFunc = currentFunc;
     nextFunc = func(nextPoint);
+
+    // This is a bugfix. Without it, the code gets lost and can't find the solution.
+    // See also the implementation at https://en.wikipedia.org/wiki/Brent%27s_method
+    if (nextFunc == 0)
+      return nextPoint;
+
     if (counterFunc * nextFunc < 0) {
       currentPoint = nextPoint;
       currentFunc = nextFunc;
diff --git a/tests/SarTests.cpp b/tests/SarTests.cpp
index cd6b21e..574b5fc 100644
--- a/tests/SarTests.cpp
+++ b/tests/SarTests.cpp
@@ -84,10 +84,10 @@ TEST_F(SarSensorModel, computeGroundPartials) {
   ASSERT_EQ(partials.size(), 6);
   EXPECT_NEAR(partials[0], 6.5128150576280552e-09, 1e-8);
   EXPECT_NEAR(partials[1], -5.1810407815840636e-15, 1e-8);
-  EXPECT_NEAR(partials[2], -0.13309947654685725, 1e-8);
+  EXPECT_NEAR(partials[2], -0.13333333443071135, 1e-8);
   EXPECT_NEAR(partials[3], -33.057625791698072, 1e-8);
   EXPECT_NEAR(partials[4], 6.1985123841926308e-05, 1e-8);
-  EXPECT_NEAR(partials[5], 0.007743051337209989, 1e-8);
+  EXPECT_NEAR(partials[5], 0.0077565105243007169, 1e-8);
 }
 
 TEST_F(SarSensorModel, imageToProximateImagingLocus) {
-- 
GitLab