【问题标题】:Should I use `strictfp` modifier when converting `float` to `double`?将“float”转换为“double”时应该使用“strictfp”修饰符吗?
【发布时间】:2018-10-13 14:56:38
【问题描述】:

如果我想编写从 float 转换为 double 的方法。

在任何情况下两者会返回不同的结果吗?

如果我不关心平台一致性,我应该使用哪个版本?

如果我需要它在不同平台上表现一致怎么办?

  double f2d(float x) {
    return (double) x;
  }

或:

  strictfp double f2d(float x) {
    return (double) x;
  }

JLS 5.1.2:

从 float 到 double 的扩展原始转换不是 strictfp 可能会丢失有关转换值整体大小的信息。

为什么此转换会丢失信息?

【问题讨论】:

标签: java floating-point strictfp


【解决方案1】:

strictfp 对 float 到 double 的转换没有影响。原因在于 Java 语言规范, 4.2.3. Floating-Point Types, Formats, and Values。特别是:

请注意,表 4.2.3-A 中的约束被设计为使得每个 浮点值集合的元素必然也是 float-extended-exponent 值集、double 值集和 双扩展指数值集。

由于float 值集的每个元素也是double 值集的一个元素,因此float 到double 的转换将是精确的,无论它是否是 FP 严格的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多