Improve accuracy of Jet derivatives

Several derivative rules lose accuracy or range. Squaring overflows in
s / x, 1 - x^2 cancels near |x| = 1 in asin and acos, and v / x
overflows in the Bessel derivative for subnormal x. Use forms without
cancellation, squaring or overflow. Reflect negative integer Bessel
orders and avoid the negative order v - 1 for 0 < v < 1, both of which
std::cyl_bessel_j rejects.

Change-Id: Ia4f83de843b01eea2a39c20a648b7805c50591b0
diff --git a/include/ceres/jet.h b/include/ceres/jet.h
index 2219023..5090b92 100644
--- a/include/ceres/jet.h
+++ b/include/ceres/jet.h
@@ -389,8 +389,10 @@
 // Binary / with a scalar: s / x
 template <typename T, int N>
 EIGEN_STRONG_INLINE Jet<T, N> operator/(T s, const Jet<T, N>& g) {
-  const T minus_s_g_a_inverse2 = -s / (g.a * g.a);
-  return Jet<T, N>(s / g.a, g.v * minus_s_g_a_inverse2);
+  // Evaluating −s / x² as −(s / x) / x avoids squaring x, which overflows or
+  // underflows although the derivative is representable.
+  const T quotient = s / g.a;
+  return Jet<T, N>(quotient, g.v * (-quotient / g.a));
 }
 
 // Binary / with a scalar: x / s
@@ -698,7 +700,9 @@
 // acos(a + h) ~= acos(a) - 1 / sqrt(1 - a^2) h
 template <typename T, int N>
 EIGEN_STRONG_INLINE Jet<T, N> acos(const Jet<T, N>& f) {
-  const T tmp = -T(1.0) / sqrt(T(1.0) - f.a * f.a);
+  // (1 − x)⋅(1 + x) avoids the cancellation of 1 − x² near |x| = 1, where
+  // 1 − x is exact.
+  const T tmp = -T(1.0) / sqrt((T(1.0) - f.a) * (T(1.0) + f.a));
   return Jet<T, N>(acos(f.a), tmp * f.v);
 }
 
@@ -711,7 +715,9 @@
 // asin(a + h) ~= asin(a) + 1 / sqrt(1 - a^2) h
 template <typename T, int N>
 EIGEN_STRONG_INLINE Jet<T, N> asin(const Jet<T, N>& f) {
-  const T tmp = T(1.0) / sqrt(T(1.0) - f.a * f.a);
+  // (1 − x)⋅(1 + x) avoids the cancellation of 1 − x² near |x| = 1, where
+  // 1 − x is exact.
+  const T tmp = T(1.0) / sqrt((T(1.0) - f.a) * (T(1.0) + f.a));
   return Jet<T, N>(asin(f.a), tmp * f.v);
 }
 
@@ -986,6 +992,12 @@
 
 inline double BesselJn(int n, double x) {
 #ifdef CERES_HAS_CPP17_BESSEL_FUNCTIONS
+  // cyl_bessel_j rejects negative orders, unlike jn. Reflect them using
+  // J₋ₙ(x) = (−1)ⁿ⋅Jₙ(x), see formula http://dlmf.nist.gov/10.4#E1.
+  if (n < 0) {
+    const double j = cyl_bessel_j(-static_cast<double>(n), x);
+    return n % 2 == 0 ? j : -j;
+  }
   return cyl_bessel_j(static_cast<double>(n), x);
 #else
   CERES_DISABLE_DEPRECATED_WARNING
@@ -1004,36 +1016,24 @@
 // j0(a + h) ~= j0(a) - j1(a) h
 template <typename T, int N>
 EIGEN_STRONG_INLINE Jet<T, N> BesselJ0(const Jet<T, N>& f) {
-#ifdef CERES_HAS_CPP17_BESSEL_FUNCTIONS
-  return cyl_bessel_j(0, f);
-#else
   return Jet<T, N>(BesselJ0(f.a), -BesselJ1(f.a) * f.v);
-#endif  // defined(CERES_HAS_CPP17_BESSEL_FUNCTIONS)
 }
 
 // See formula http://dlmf.nist.gov/10.6#E1
 // j1(a + h) ~= j1(a) + 0.5 ( j0(a) - j2(a) ) h
 template <typename T, int N>
 EIGEN_STRONG_INLINE Jet<T, N> BesselJ1(const Jet<T, N>& f) {
-#ifdef CERES_HAS_CPP17_BESSEL_FUNCTIONS
-  return cyl_bessel_j(1, f);
-#else
   return Jet<T, N>(BesselJ1(f.a),
                    T(0.5) * (BesselJ0(f.a) - BesselJn(2, f.a)) * f.v);
-#endif  // defined(CERES_HAS_CPP17_BESSEL_FUNCTIONS)
 }
 
 // See formula http://dlmf.nist.gov/10.6#E1
 // j_n(a + h) ~= j_n(a) + 0.5 ( j_{n-1}(a) - j_{n+1}(a) ) h
 template <typename T, int N>
 EIGEN_STRONG_INLINE Jet<T, N> BesselJn(int n, const Jet<T, N>& f) {
-#ifdef CERES_HAS_CPP17_BESSEL_FUNCTIONS
-  return cyl_bessel_j(n, f);
-#else
   return Jet<T, N>(
       BesselJn(n, f.a),
       T(0.5) * (BesselJn(n - 1, f.a) - BesselJn(n + 1, f.a)) * f.v);
-#endif  // defined(CERES_HAS_CPP17_BESSEL_FUNCTIONS)
 }
 
 #endif  // defined(CERES_HAS_CPP17_BESSEL_FUNCTIONS) ||
@@ -1045,15 +1045,21 @@
 // j_n(a + h) ~= j_n(a) + 0.5 ( j_{n-1}(a) - j_{n+1}(a) ) h
 template <typename T, int N>
 EIGEN_STRONG_INLINE Jet<T, N> cyl_bessel_j(double v, const Jet<T, N>& f) {
-  // See formula http://dlmf.nist.gov/10.6#E3
-  // j0(a + h) ~= j0(a) - j1(a) h
+  const T j = cyl_bessel_j(v, f.a);
+  // d/dx J₀(x) = −J₁(x), see formula http://dlmf.nist.gov/10.6#E3.
   if (fpclassify(v) == FP_ZERO) {
-    return Jet<T, N>(cyl_bessel_j(0, f.a), -cyl_bessel_j(1, f.a) * f.v);
+    return Jet<T, N>(j, -cyl_bessel_j(1, f.a) * f.v);
+  }
+  // d/dx Jᵥ(x) = v⋅Jᵥ(x) / x − Jᵥ₊₁(x) avoids the negative order v − 1, see
+  // formula http://dlmf.nist.gov/10.6#E2.
+  if (v < 1) {
+    // Dividing j by x first avoids the overflow of v / x for subnormal x.
+    const T derivative = v * (j / f.a) - cyl_bessel_j(v + 1, f.a);
+    return Jet<T, N>(j, derivative * f.v);
   }
 
   return Jet<T, N>(
-      cyl_bessel_j(v, f.a),
-      T(0.5) * (cyl_bessel_j(v - 1, f.a) - cyl_bessel_j(v + 1, f.a)) * f.v);
+      j, T(0.5) * (cyl_bessel_j(v - 1, f.a) - cyl_bessel_j(v + 1, f.a)) * f.v);
 }
 
 #endif  // CERES_HAS_CPP17_BESSEL_FUNCTIONS
diff --git a/internal/ceres/jet_test.cc b/internal/ceres/jet_test.cc
index dea4b70..108257f 100644
--- a/internal/ceres/jet_test.cc
+++ b/internal/ceres/jet_test.cc
@@ -89,6 +89,13 @@
   return RelativelyNear(expected, kTolerance);
 }
 
+// Matches a double within kTolerance relative to a nonzero expected value.
+// Unlike RelativelyNear, which compares absolutely once either value is zero,
+// this rejects an actual value of zero for a tiny expected value.
+auto IsNearNonzero(double expected) {
+  return ::testing::DoubleNear(expected, std::fabs(expected) * kTolerance);
+}
+
 // Matches a Jet whose parts are each equal to those of expected.
 ::testing::Matcher<J> JetEq(const J& expected) {
   return ::testing::AllOf(
@@ -287,7 +294,30 @@
 #ifndef _MSC_VER
   EXPECT_THROW(cyl_bessel_j(-1, zero), std::domain_error);
 #endif  // defined(_MSC_VER)
+
+  // Fractional orders below 1 have no order v - 1 that cyl_bessel_j accepts.
+  // References computed with mpmath.
+  EXPECT_THAT(cyl_bessel_j(0.5, MakeJet(1.0, 1.0, 0.0)),
+              RelativelyNear(MakeJet(0.671396707141803090416364,
+                                     0.09540051444747453431233896,
+                                     0.0),
+                             kRelaxedTolerance));
+  EXPECT_THAT(cyl_bessel_j(0.25, MakeJet(2.0, 1.0, 0.0)),
+              RelativelyNear(MakeJet(0.3978110643381783487252207,
+                                     -0.4964470409980117469133667,
+                                     0.0),
+                             kRelaxedTolerance));
+
+  // At a subnormal x, v / x overflows although v⋅Jᵥ(x) / x is finite. The
+  // reference is the derivative of J_{1/2}(x) = √(2 / (πx))⋅sin(x) computed
+  // with SymPy at x = 2^-1030.
+  EXPECT_THAT(cyl_bessel_j(0.5, MakeJet(0x1p-1030, 1.0, 0.0)).v[0],
+              IsNearNonzero(4.279153176604569758917400e+154));
 #endif  // defined(CERES_HAS_CPP17_BESSEL_FUNCTIONS)
+
+  // J_{-n}(x) = (-1)^n J_n(x), see formula http://dlmf.nist.gov/10.4.E1
+  EXPECT_THAT(BesselJn(-1, z), IsAlmostEqualTo(-BesselJn(1, z)));
+  EXPECT_THAT(BesselJn(-2, z), IsAlmostEqualTo(BesselJn(2, z)));
 }
 #endif  // defined(CERES_HAS_POSIX_BESSEL_FUNCTIONS) ||
         // defined(CERES_HAS_CPP17_BESSEL_FUNCTIONS)
@@ -1006,6 +1036,25 @@
   }
 }
 
+TEST(Jet, ScalarDividedByJetExtremeMagnitudes) {
+  // d/dx s / x = -s / x^2, whose denominator underflows or overflows although
+  // the derivative is representable. References computed with mpmath.
+  EXPECT_THAT((1e-200 / MakeJet(1e-170, 1.0, 0.0)).v[0],
+              RelativelyNear(-1e140, kTolerance));
+  EXPECT_THAT((1e300 / MakeJet(1e200, 1.0, 0.0)).v[0], IsNearNonzero(-1e-100));
+}
+
+TEST(Jet, InverseSineAndCosineNearOne) {
+  // 1 - a^2 cancels in the derivative 1 / sqrt(1 - a^2) once a^2 is rounded.
+  // The reference is computed with mpmath.
+  const double a = 1.0 - std::ldexp(1.0, -27);
+  constexpr double kDerivative = 8192.000015258789105132564;
+  EXPECT_THAT(asin(MakeJet(a, 1.0, 0.0)).v[0],
+              RelativelyNear(kDerivative, kTolerance));
+  EXPECT_THAT(acos(MakeJet(a, 1.0, 0.0)).v[0],
+              RelativelyNear(-kDerivative, kTolerance));
+}
+
 static_assert(std::is_same_v<decltype(+std::declval<const J&>()), J>,
               "Unary plus must return a Jet by value, since a reference "
               "dangles when the operand is a temporary.");