Java 语言规范 point 3.10.2规定浮点值按照 IEEE 754 标准中的指定进行转换。对于 strtod
,C 标准指定了函数如何将文本转换为浮点值。就表述本身而言,两者似乎涵盖了相同的案例。我不确定的是,舍入规则如何? Java 编译器执行的转换是否与 strtod
执行的转换不同?
背景是我想编译为 Java 字节码代码,因此需要将 float/double 值的文本表示转换为类文件中的表示。
例如,以下 Java 代码打印更精确的值:
double value = 1.23412991913372577889911;
System.out.println(value);
// Output: 1.2341299191337258
使用 strtod 转换相同的值并将其打印出来打印一个不太精确的值:
const char* textual = "1.23412991913372577889911";
double result = strtod(textual, ...);
std::cout << result << std::endl;
// Output: 1.23413
这是输出问题,还是值实际上以不同的方式转换?
编辑:正如 Pascal Cuoq 评论的那样,当以全精度打印出值时(我通过设置 std::cout. precision()
这样做),这些值相等,所以我假设转换会产生相同的值。我想我会为此做一个测试。 :-)
最佳答案
是的,存在差异。这是我能找到的两个。
Java 支持数字之间使用下划线。从规范来看:
Underscores are allowed as separators between digits that denote the whole-number part, and between digits that denote the fraction part, and between digits that denote the exponent.
对于您的情况来说,这应该不是问题。您只需删除所有下划线。
Java 强制执行 IEEE 754 浮点算术的舍入到最接近的规则。来自 Java spec (语言规范引用
Double.valueOf
):[This] exact numerical value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type double by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic, which includes preserving the sign of a zero value.
strtod 的舍入模式是实现定义的,IIUC 甚至允许 1 ULP 的误差。来自 C99 规范(
strtod
文档引用第 6.4.4.2 节):For decimal floating constants, and also for hexadecimal floating constants when FLT_RADIX is not a power of 2, the result is either the nearest representable value, or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner.
仅当您的 C 编译器支持附录 F:IEC 60559 浮点运算时,
strtod
才保证符合 IEEE 754(IEC 60559 和 IEEE 754 是等效的) :The translation time conversion of floating constants and the strtod, strtof, strtold, fprintf, fscanf, and related library functions in <stdlib.h>, <stdio.h>, and <wchar.h> provide IEC 60559 binary-decimal conversions.
另请注意,strtod
仅从 C99 开始(Java 从版本 5 开始)才支持十六进制浮点表示法。因此,请检查您的 strtod
实现的行为方式。
关于java - Java 编译器的文本到浮点值转换与 strtod 有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33734934/