Skip to content

Pow(-1, n) throws OverflowException for any integer |n| ≥ 2^31, although the result is ±1 #128

Description

@matt-edmondson

What's wrong

The integer-power path in Pow (PreciseNumber/PreciseNumber.cs:1818) loops over power.Abs().To<int>(), so an exponent that doesn't fit in an int throws. IsUnit already short-circuits a base of +1, but a base of −1 gets no such shortcut, even though (−1)^n is always ±1.

Repro

Parse("-1").Pow(Parse("2147483648"));   // OverflowException, expected 1
Parse("-1").Pow(Parse("-2147483648"));  // OverflowException, expected 1
Parse("-1").Pow(Parse("1e20"));         // OverflowException, expected 1
Parse("-1").Pow(Parse("2147483647"));   // -1 (correct)
Parse("1").Pow(Parse("1e20"));          // 1 (correct, short-circuited)

For comparison, double.Pow(-1, 1e20) returns 1.

Suggested fix / acceptance criteria

  • Before the loop, when the base is −1, return IsEvenInteger(power) ? One : NegativeOne.
  • For any other base, an exponent that large really does overflow the result's exponent, so the current exception is fine there.
  • Add tests for the three failing calls above.

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugSomething isn't workingreadyFully specified; implement as written

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions