From: Simon Tatham Date: Wed, 16 Apr 2025 06:33:49 +0000 (+0100) Subject: Actually, better if quadratic3 also returns an Option X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ian/git?a=commitdiff_plain;h=f0c08c413bc12fec2a417bc5f1e6e920c1a18d2e;p=nimber.git Actually, better if quadratic3 also returns an Option --- diff --git a/src/finite.rs b/src/finite.rs index f430bcd..ac74298 100644 --- a/src/finite.rs +++ b/src/finite.rs @@ -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), (