【问题标题】:why there is no ArithmeticException( divide by zero) when both values are double? [duplicate]当两个值都是双倍时,为什么没有 ArithmeticException(除以零)? [复制]
【发布时间】:2014-01-05 03:06:28
【问题描述】:

看过Double.java的源码和一些常量是这样的

/**
 * 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;

但我想知道为什么它不抛出 ArithmeticException(除以零)?

我试过了

 public static final int VALUE = 0/0;

现在它正在抛出异常,但是当我说时

 public static final double VALUE = 0d/0d;

它没有抛出异常...

Double 有什么魔力,为什么它不抛出异常?

【问题讨论】:

  • 因为双 0 永远不是 0,它通常用 NaN 表示
  • 可能是因为0d并不完全是0,而是一个非常接近的值
  • @blackbelt你能解释清楚吗...如果0不是0当它是double时,那么0的值是多少?
  • @GopalRao 见斯蒂芬回答

标签: java android exception math


【解决方案1】:

因为在数字系统中未定义的东西无法明显表示。 “未定义”不是数字 (NaN),double/float 有 NaN 来表示。

IEEE 754

“算术格式:二进制和十进制浮点数据集,由有限数(包括有符号零和次正规数)、无穷大和特殊的“非数字”值 (NaN) 组成”

【讨论】:

  • Ermm ... NaN 不代表无穷大。 INF 代表无穷大。零除以零是“不确定的”。
【解决方案2】:

Java(以及一些但不是所有其他语言)中的双精度值支持 NaN(非数字)值。

除以 0 之类的操作会给你一个双精度值,即 NaN。

任何涉及 NaN 的操作也会导致 NaN。

维基百科有一整页关于 NaN 的主题:

http://en.wikipedia.org/wiki/NaN

【讨论】:

    【解决方案3】:

    “神奇”在于 Java 浮点表示基于 IEE 754 floating point 标准。这有一个特殊值 (NaN),表示当零除以零时得到的“不确定值”。 (也有代表正无穷和负无穷的值;例如,1.0 / 0.0 给出 INF - 正无穷。)

    这在 Java 语言规范中有介绍;请参阅讨论表示的§4.2.3 部分和讨论算术工作原理的§4.2.4 部分。


    请注意,同样的“魔法”适用于 floatdoubleFloatDouble

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      相关资源
      最近更新 更多