【问题标题】:Strictfp returns different results on different systemsStrictfp 在不同的系统上返回不同的结果
【发布时间】:2016-04-14 12:16:19
【问题描述】:

我在 Windows 8 (Intel Atom Z3775) 上使用以下方法:

public static strictfp void main(String args[])
{
    float a = 0.000000002f;
    float b = 90000300000000004f;
    float c = a * b;
    System.out.println(c);
}

这给了我:1.80000592E8

运行时

public strictfp void calculate()
{
    float a = 0.000000002f;
    float b = 90000300000000004f;
    float c = a * b;
    Toast.makeText(getApplicationContext(), c + "", Toast.LENGTH_LONG).show();
}

我得到:1.8000059E8

它们为什么不同?是不是我用的 strictfp 错了?

【问题讨论】:

  • 如果在这两种情况下都打印String.format("%08x", Float.floatToIntBits(c)) 会发生什么?
  • 它们返回完全相同的字符串。在两个平台上使用 Float.toString(c) 转换为 String 没有帮助。
  • 正确 - 所以实际数字是按位相同的。将浮点数转换为字符串的算法的实现只是有所不同。

标签: java floating-point strictfp


【解决方案1】:

您已确认打印浮点数的十六进制表示显示值相同:

String.format("%08x", Float.floatToIntBits(c))

这意味着float 转换为String 的实现方式有所不同。

请注意,OpenJDK implementation of java.lang.Float.toString(float) 调用来自 sun.misc.FloatingDecimal 的方法 - 即它是特定于 JDK 的实现。

你需要:

  • 确保您始终使用相同的实现来运行代码
  • 提供您自己的实现,始终产生相同的结果
  • 指定更短的格式,以便字符串与小数位数相同。

【讨论】:

    【解决方案2】:

    嗯,显示方式肯定不一样……

    【讨论】:

    • 这会改变什么?我现在向 System.out.println() 添加了一个 '+ " "',现在两个浮点数都首先转换为字符串,然后再提供给方法。
    • 显然浮点到字符串的转换也可以不同。
    • @user2912528 你必须自己实现浮点到字符串的转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多