From 5f731703d843c1addd31439c10b39de376518c89 Mon Sep 17 00:00:00 2001 From: Yanhu007 Date: Wed, 15 Apr 2026 10:08:23 +0800 Subject: [PATCH] fix: support negative base with integer exponent in Pow Pow(-2, 3) previously panicked with "Pow: negative base", even though (-2)^3 = -8 is well-defined. This matches the behavior of math.Pow from the standard library. Now handles negative base when the exponent is an integer by computing |z|^w and negating the result for odd exponents. Still panics for negative base with non-integer exponent (which would require complex numbers). Fixes #35 --- pow.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/pow.go b/pow.go index 89fe8da..884492c 100644 --- a/pow.go +++ b/pow.go @@ -3,11 +3,24 @@ package bigfloat import "math/big" // Pow returns a big.Float representation of z**w. Precision is the same as the one -// of the first argument. The function panics when z is negative. +// of the first argument. The function panics when z is negative and w is +// not an integer. func Pow(z *big.Float, w *big.Float) *big.Float { if z.Sign() < 0 { - panic("Pow: negative base") + // For negative base, handle integer exponents: (-z)^n = (-1)^n * z^n + if w.IsInt() { + // Compute |z|^w + abs := new(big.Float).Abs(z) + result := Pow(abs, w) + // If exponent is odd, negate the result + wInt, _ := w.Int(nil) + if wInt.Bit(0) == 1 { // odd + result.Neg(result) + } + return result + } + panic("Pow: negative base with non-integer exponent") } // Pow(z, 0) = 1.0