比较从文本文件中读取的双精度数
Comparing doubles read from a text file
我正在比较文本文件中的一个双精度值和一个硬编码的双精度值,使用 Java 中的 Double.parseDouble() 从文本文件读取的值被放入一个双精度变量中。然后,我使用以下行来声明它们的相等性。这个断言有可能失败吗?是否取决于价值?
assertEquals(17353820.450663020000, Double.parseDouble(input.next()), 0.0);
请注意,0.0 是用于比较双精度值的 epsilon 值。
文本文件内容:
17353820.450663020000
任何语言中的浮点数和双精度数都有精度限制,因此可以近似为字符串格式。有关一些信息,请参阅 https://floating-point-gui.de。这就是 epsilon 参数的用途,它表示当不能完全匹配时,必须考虑要测试的值有多接近 "correct"。
Is it possible that this assert fails?
没有
Does it depend on the value?
没有
JavaparseDouble
的文档说:
Returns a new double
initialized to the value represented by the specified String
, as performed by the valueOf
method of class Double
.
Java 语言规范,第 3.10.2. Floating-Point Literals 节说:
The details of proper input conversion from a Unicode string representation of a floating-point number to the internal IEEE 754 binary floating-point representation are described for the methods valueOf
of class Float
and class Double
of the package java.lang
.
如您所见,编译器使用与 parseDouble
方法相同的逻辑来解析双精度值,因此结果始终相同。
我正在比较文本文件中的一个双精度值和一个硬编码的双精度值,使用 Java 中的 Double.parseDouble() 从文本文件读取的值被放入一个双精度变量中。然后,我使用以下行来声明它们的相等性。这个断言有可能失败吗?是否取决于价值?
assertEquals(17353820.450663020000, Double.parseDouble(input.next()), 0.0);
请注意,0.0 是用于比较双精度值的 epsilon 值。
文本文件内容:
17353820.450663020000
任何语言中的浮点数和双精度数都有精度限制,因此可以近似为字符串格式。有关一些信息,请参阅 https://floating-point-gui.de。这就是 epsilon 参数的用途,它表示当不能完全匹配时,必须考虑要测试的值有多接近 "correct"。
Is it possible that this assert fails?
没有
Does it depend on the value?
没有
JavaparseDouble
的文档说:
Returns a new
double
initialized to the value represented by the specifiedString
, as performed by thevalueOf
method of classDouble
.
Java 语言规范,第 3.10.2. Floating-Point Literals 节说:
The details of proper input conversion from a Unicode string representation of a floating-point number to the internal IEEE 754 binary floating-point representation are described for the methods
valueOf
of classFloat
and classDouble
of the packagejava.lang
.
如您所见,编译器使用与 parseDouble
方法相同的逻辑来解析双精度值,因此结果始终相同。