这种 Java 双重解析行为是否符合规范?
2022-09-01 23:12:14
该方法以不一致的方式处理奇怪的双精度表示。java.lang.Double.parseValue
如果你写了一个非常大的数字,大到它超出了 的范围,但随后附加一个大的负指数以使其回到范围内,你最终会进入范围(如Scala的REPL所示):double
scala>
java.lang.Double.parseDouble("10000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000001e-400")
res25: Double = 1.0E-21
另一方面,如果你写一个非常小的数字,小到它超出了 的范围,但随后使用一个大的正指数将其带回范围,它只在指数本身不太大时才有效:double
scala>
java.lang.Double.parseDouble("0.000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000001e400")
res26: Double = Infinity
scala>
java.lang.Double.parseDouble("0.000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000001e200")
res27: Double = 1.0E-179
这仅仅是一个错误,还是在某个地方有一个规范允许这种行为,或者规范允许所有这些行为都失败,当一个人得到正确的结果时,人们应该感谢自己的祝福?(如果是错误,是否已修复?
(题外话:我正在编写自定义字符串到双精度代码,并且打算在棘手的情况下遵从Java默认实现,但是这个测试用例失败了。