Skip to content

Pow(0, y) returns 0 for negative y, but 1/0 and RootN(0, -n) throw DivideByZeroException #110

Description

@matt-edmondson

What's wrong

In the instance Pow (PreciseNumber/PreciseNumber.cs ~L1755), the zero-base branch runs before the sign of power is checked:

if (power.Significand.IsZero) return One;
else if (Significand.IsZero) return Zero;   // runs for negative power as well

The static Pow (PreciseNumber.Exponentials.cs) forwards to this method, so it has the same bug.

0^-y is 1/0^y, which is a division by zero. PreciseNumber has no infinity, and everywhere else it handles this case by throwing:

  • One / Zero throws DivideByZeroException
  • RootN(0, -2) explicitly throws DivideByZeroException (Roots.cs ~L159)

Failure scenario (reproduced)

  • PreciseNumber.Pow(0, -1) returns 0, where the mathematical answer is unbounded and Math.Pow(0, -1) gives +∞
  • PreciseNumber.Pow(0, -0.5) returns 0
  • 1 / 0 throws DivideByZeroException
  • RootN(0, -2) throws DivideByZeroException

Generic-math code such as T.Pow(x, -1) that runs over PreciseNumber gets a finite, wrong answer without any error.

Suggested fix

In the zero-base branch, return Zero only when power > 0, and throw DivideByZeroException when power < 0. Document the exception with an <exception> tag, as RootN does.

Acceptance criteria

  • Pow(0, -1) and Pow(0, -0.5) throw DivideByZeroException.
  • Pow(0, 2) still returns 0 and Pow(0, 0) still returns 1.

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 working

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions