chiark / gitweb /
Actually, better if quadratic3 also returns an Option
authorSimon Tatham <anakin@pobox.com>
Wed, 16 Apr 2025 06:33:49 +0000 (07:33 +0100)
committerSimon Tatham <anakin@pobox.com>
Wed, 16 Apr 2025 18:30:13 +0000 (19:30 +0100)
src/finite.rs

index f430bcd22348e339c9b2bf222932183ff32aecd1..ac74298c0c843bdc852a3a4a30f65ab7a9049ea4 100644 (file)
@@ -1272,8 +1272,8 @@ impl FiniteNimber {
     }
 
     /// Compute the solutions to a quadratic equation in the most
-    /// general form a\*x^2 + b\*x + c, for constants a,b,c. This
-    /// function panics if `a == 0`.
+    /// general form a\*x^2 + b\*x + c, for constants a,b,c. Returns
+    /// `None` if `a == 0`.
     ///
     /// The two values of x are returned in numerical order.
     ///
@@ -1285,7 +1285,7 @@ impl FiniteNimber {
     /// let a = FiniteNimber::from(0x17320508);
     /// let b = FiniteNimber::from(0x16180339);
     /// let c = FiniteNimber::from(0x14142135);
-    /// let (x0, x1) = FiniteNimber::quadratic3(&a, &b, &c);
+    /// let (x0, x1) = FiniteNimber::quadratic3(&a, &b, &c).unwrap();
     ///
     /// // The two solutions are different
     /// assert_ne!(x0, x1);
@@ -1298,11 +1298,11 @@ impl FiniteNimber {
         a: &Self,
         b: &Self,
         c: &Self,
-    ) -> (FiniteNimber, FiniteNimber) {
+    ) -> Option<(FiniteNimber, FiniteNimber)> {
         // Strategy: we reduce this to the quadratic2() case by
         // dividing through by a.
-        let ainv = a.inverse().expect("Division by zero");
-        Self::quadratic2(&(b * &ainv), &(c * &ainv))
+        let ainv = a.inverse()?;
+        Some(Self::quadratic2(&(b * &ainv), &(c * &ainv)))
     }
 }
 
@@ -1814,6 +1814,12 @@ mod tests {
         assert_eq!(x0, x1);
         assert_eq!(x0, c.sqrt());
 
+        // Degenerate case of quadratic3 with a=0, checking it returns None.
+        assert_eq!(
+            FiniteNimber::quadratic3(&FiniteNimber::from(0), &c, &c),
+            None
+        );
+
         // A large random example for quadratic2
         let b = FiniteNimber::from(&[
             0x6a784d9045190cfe,
@@ -1887,7 +1893,7 @@ mod tests {
             0x5f39cc0605cedc83,
             0x19e3779b97f4a7c1,
         ]);
-        let (x0, x1) = FiniteNimber::quadratic3(&a, &b, &c);
+        let (x0, x1) = FiniteNimber::quadratic3(&a, &b, &c).unwrap();
         assert_eq!(
             (&x0, &x1),
             (