简体   繁体   English

浮点算法和浮点值比较

[英]Floating point arithmetic and comparing of floating point values

For these lines of code, I get back 0 as an output that is they are all equal to each other. 对于这些代码行,我得到0作为输出,因为它们彼此相等。 Now if I understand correctly, ab and c may store slightly different versions of the true value .3 hence when do a Float.compare(...) against these values, I expect to get back as an output a value other than 0. Why do I get them as 0? 现在,如果我理解正确,那么ab和c可能会存储真正值.3的稍有不同的版本,因此,当对这些值进行Float.compare(...)时,我希望返回的值不是0。为什么我将它们设为0?

float a = 0.15f + 0.15f;
float b = 0.1f + 0.2f;
float c = 0.3f;
System.out.println(Float.compare(a,  b));  //<--- outputs 0
System.out.println(Float.compare(a,  c));  //<--- outputs 0
System.out.println(Float.compare(b,  c));  //<--- outputs 0

Because, as you say, they may store slightly different versions. 因为,正如您所说,它们可能存储略有不同的版本。 But with these simple expressions, there is no loss of precision, so a, b and c all contain exactly the same version of .3f . 但是有了这些简单的表达式,就不会损失精度,因此a,b和c都包含完全相同的.3f版本。

For fun, try this. 为了好玩,试试这个。 Here you will lose precision, and the result of the comparison will not be 0 : 在这里您将失去精度,并且比较的结果将不是0

public static void main(String[] args) {
    float a = .3f;
    float b = .3f;
    a = (float) Math.cos(a);
    a = (float) Math.acos(a);
    System.out.println(Float.compare(a, b));
}

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

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