Claudio P
Claudio P

Reputation: 2203

Double divide by zero: Why is the result inconsistent?

Why are the results of:

double a = 0.0/0.0;
double b = 0/0.0;

= NaN

But the results of for example:

double e = 0.1/0.0;
double e = 12.0/0.0;
double f = 1.0/0.0;

= Infinity

I understand that double or float divisions are somehow a little bit different. I am pretty happy with the resulting NaN because the result is not defined when something is divided by zero. But why they defined that the result of something greater than zero divided by zero is Infitity? Has this something todo with the method they use to perform the division of floating points?

Upvotes: 2

Views: 1678

Answers (3)

dumbPotato21
dumbPotato21

Reputation: 5705

JLS 15.17.2 clearly states that

Division of a zero by a zero results in NaN; division of zero by any other finite value results in a signed zero. The sign is determined by the rule stated above.

Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

The JLS also says about the difference between these constants in operations.

If either operand is NaN, the result is NaN.

Division of an infinity by an infinity results in NaN.

Division of an infinity by a finite value results in a signed infinity. The sign is determined by the rule stated above.

Not inconsistent at all.

Upvotes: 3

Brick
Brick

Reputation: 4272

There are other answers that specify that this is in the standard and therefore "expected" behavior. You seem to want to know why the standard is like that. I would guess that the reason is that some expressions have well-defined limits (as in calculus) and some do not even have a limit. The ones with a well-defined limit get a signed infinity (since that is the limit). The ones like 0/0 get NaN because there is no limit there. (The limit from the left is negative infinity and the limit from the right is positive infinity.) In all cases, when I say "limit", I mean limit of n/x as x -> 0, where n is the fixed numerator.

Upvotes: 2

According to math definition following operations result in an undetermined result and that is what NAN represent! Following undetermined result can be:

  • 0/0,
  • ∞/∞,
  • 0*∞,
  • ∞-∞,
  • 0^0,
  • 1^∞,
  • 0^∞

java match almost all of them (except ∞^0 and 0^0)

    // 0/0
    double a = 0.0 / 0.0;
    System.out.println(a);
    // ∞/∞
    a = Double.POSITIVE_INFINITY / Double.POSITIVE_INFINITY;
    System.out.println(a);
    // 0*∞
    a = 0 * Double.POSITIVE_INFINITY;
    System.out.println(a);
    // ∞-∞
    a = Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY;
    System.out.println(a);
    // 0^0
    a = Math.pow(0, 0);
    System.out.println(a);
    // 1^∞
    a = Math.pow(1, Double.POSITIVE_INFINITY);
    System.out.println(a);
    // ∞^0
    a = Math.pow(Double.POSITIVE_INFINITY, 0);
    System.out.println(a);

Upvotes: 2

Related Questions