简体   繁体   English

比较从文本文件中读取的双打

[英]Comparing doubles read from a text file

I am comparing one double from a text file with a hard-coded double, the value read from a text file is put into a double variable using Double.parseDouble() in Java.我将文本文件中的双精度数与硬编码双精度数进行比较,使用 Java 中的 Double.parseDouble() 将从文本文件中读取的值放入双精度变量中。 Then, I'm using the following line to assert their equality.然后,我使用以下行来断言它们的相等性。 Is it possible that this assert fails?这个断言有可能失败吗? Does it depend on the value?它取决于价值吗?

assertEquals(17353820.450663020000, Double.parseDouble(input.next()), 0.0);

Note that 0.0 is the value of epsilon used for comparing doubles.请注意,0.0 是用于比较双打的 epsilon 值。

Text file contents:文本文件内容:

17353820.450663020000

Is it possible that this assert fails?这个断言有可能失败吗?

No.不。

Does it depend on the value?它取决于价值吗?

No.不。


Javadoc of parseDouble says: parseDouble Javadoc 说:

Returns a new double initialized to the value represented by the specified String , as performed by the valueOf method of class Double .返回一个新的double初始化为由指定的String表示的值,Double类的valueOf方法执行

The Java Language Specification, section 3.10.2. Java 语言规范,第3.10.2 Floating-Point Literals says: 浮点文字说:

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 .描述了从浮点数的 Unicode 字符串表示到内部 IEEE 754 二进制浮点表示的正确输入转换的详细信息,用于java.lang FloatDouble类的valueOf方法

As you can see, the compiler uses he same logic for parsing doubles as the parseDouble method, so the result will always be the same.如您所见,编译器使用与parseDouble方法相同的逻辑来解析双精度parseDouble ,因此结果将始终相同。

Floats and doubles in any language have a limit on precision, so can be approximations to the string format.任何语言中的浮点数和双精度数都有精度限制,因此可以是字符串格式的近似值。 See https://floating-point-gui.de for some information.有关一些信息,请参阅https://floating-point-gui.de That's what the epsilon argument is for, it says how close the value being tested has to be to be considered "correct" when it can't be an exact match.这就是 epsilon 参数的用途,它表示当不能完全匹配时,被测试的值必须有多接近才能被认为是“正确的”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM