Double divide by zero: Why is the result inconsistent?
为什么结果如下:
1 2 | double a = 0.0/0.0; double b = 0/0.0; |
= NaN
但结果例如:
1 2 3 | double e = 0.1/0.0; double e = 12.0/0.0; double f = 1.0/0.0; |
=无限
我知道
JLS 15.17.2明确指出
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.
JLS还说明了这些常量在操作中的区别。
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.
完全没有矛盾。
根据数学定义,操作后会导致结果不确定,这就是NAN所代表的!
未确定结果可能是:
- 0/0,
- ∞/∞,
- 0 *∞,
- ∞-∞,
- 0 ^ 0,
- 1 ^∞,
- 0 ^∞
java匹配几乎所有这些(除了∞^ 0和0 ^ 0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // 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); |
还有其他答案指出这是标准的,因此是"预期的"行为。你似乎想知道为什么这个标准是这样的。我猜想原因是某些表达式有明确定义的限制(如在微积分中),有些甚至没有限制。具有明确定义限制的那些获得有符号无穷大(因为这是限制)。像0/0这样的人获得NaN,因为那里没有限制。 (左边的极限是负无穷大,右边的极限是正无穷大。)在所有情况下,当我说"极限"时,我的意思是