当两个值都为double时,为什么没有ArithmeticException(除以零)? [英] why there is no ArithmeticException( divide by zero) when both values are double?
问题描述
Double.java的可见源代码和一些常量就像
/*** {@code double}类型的非数字(NaN)值的常量.*/公共静态最终双精度NaN = 0.0/0.0;/*** {@code double}类型的正无穷大值的常数.*/公共静态最终双精度POSITIVE_INFINITY = 1.0/0.0;/*** {@code double}类型的负无穷大值的常数.*/公共静态最终双倍NEGATIVE_INFINITY = -1.0/0.0;
但是我不知道为什么它没有抛出ArithmeticException(被零除)吗?
我已经尝试过
public static final int VALUE = 0/0;
现在抛出异常,但是当我说
public static final double VALUE = 0d/0d;
这不会引发异常...
Double
的神奇之处是什么,为什么它不引发异常?
魔术"是Java浮点表示法基于 IEE 754浮点标准.它有一个特殊值(NaN),表示当零除以零时获得的不确定值".(也有一些值表示正无穷大和负无穷大;例如, 1.0/0.0
给出 INF
-正无穷大.)
这在Java语言规范中有介绍;请参见§4.2.3,其中讨论了表示形式和§4.2.4讨论算术的工作原理.
请注意,相同的魔术"适用于 float
, double
, Float
和 Double
.>
Seen source code of Double.java and some constants are like
/**
* Constant for the Not-a-Number (NaN) value of the {@code double} type.
*/
public static final double NaN = 0.0 / 0.0;
/**
* Constant for the positive infinity value of the {@code double} type.
*/
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
/**
* Constant for the negative infinity value of the {@code double} type.
*/
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
but I wonder why it is not throwing ArithmeticException(divide by zero)?
and I have tried
public static final int VALUE = 0/0;
now it's throwing Exception but when I say
public static final double VALUE = 0d/0d;
it is not throwing exception...
What's the magic of Double
and why it is not throwing Exception?
The "magic" is that Java floating point representations are based on the IEE 754 floating point standard. This has a special value (NaN) that denotes the "indefinite value" that you get when zero is divided by zero. (There are also values that represent positive and negative infinity; e.g. 1.0 / 0.0
gives INF
- positive infinity.)
This is covered in the Java Language Specification; see sections §4.2.3 which discusses the representations and §4.2.4 which discusses how arithmetic works.
Note that the same "magic" applies to float
, double
, Float
and Double
.
这篇关于当两个值都为double时,为什么没有ArithmeticException(除以零)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!