Skip to content

fix: support negative base with integer exponent in Pow#40

Open
Yanhu007 wants to merge 1 commit into
ALTree:masterfrom
Yanhu007:fix/pow-negative-base-integer
Open

fix: support negative base with integer exponent in Pow#40
Yanhu007 wants to merge 1 commit into
ALTree:masterfrom
Yanhu007:fix/pow-negative-base-integer

Conversation

@Yanhu007

Copy link
Copy Markdown

Fixes #35

Problem

Pow(z, w) panics for any negative z, even when w is an integer — a case where the result is well-defined:

bigfloat.Pow(big.NewFloat(-2), big.NewFloat(3))
// PANIC: "Pow: negative base"
// Expected: -8

This is inconsistent with math.Pow(-2, 3) == -8 from the standard library.

Fix

For negative base with integer exponent, compute |z|^w and negate the result for odd exponents:

(-z)^n = z^n     if n is even
(-z)^n = -(z^n)  if n is odd

Still panics for negative base with non-integer exponent (which would require complex numbers).

Pow(big.NewFloat(-2), big.NewFloat(3))  // → -8
Pow(big.NewFloat(-2), big.NewFloat(4))  // → 16
Pow(big.NewFloat(-3), big.NewFloat(0))  // → 1

All existing tests pass.

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 ALTree#35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Panic in Pow for negative base with integer exponent

1 participant