What's wrong with using == to compare floats i

2018-12-31 04:15发布

According to this java.sun page == is the equality comparison operator for floating point numbers in Java.

However, when I type this code:

if(sectionID == currentSectionID)

into my editor and run static analysis, I get: "JAVA0078 Floating point values compared with =="

What is wrong with using == to compare floating point values? What is the correct way to do it? 

21条回答
浮光初槿花落
2楼-- · 2018-12-31 04:53

As of today, the quick & easy way to do it is:

if (Float.compare(sectionID, currentSectionID) == 0) {...}

However, the docs do not clearly specify the value of the margin difference (an epsilon from @Victor 's answer) that is always present in calculations on floats, but it should be something reasonable as it is a part of the standard language library.

Yet if a higher or customized precision is needed, then

float epsilon = Float.MIN_NORMAL;  
if(Math.abs(sectionID - currentSectionID) < epsilon){...}

is another solution option.

查看更多
不再属于我。
3楼-- · 2018-12-31 04:53

First of all, are they float or Float? If one of them is a Float, you should use the equals() method. Also, probably best to use the static Float.compare method.

查看更多
看淡一切
4楼-- · 2018-12-31 04:55

Two different calculations which produce equal real numbers do not necessarily produce equal floating point numbers. People who use == to compare the results of calculations usually end up being surprised by this, so the warning helps flag what might otherwise be a subtle and difficult to reproduce bug.

查看更多
无与为乐者.
5楼-- · 2018-12-31 04:57

Here is a very long (but hopefully useful) discussion about this and many other floating point issues you may encounter: What Every Computer Scientist Should Know About Floating-Point Arithmetic

查看更多
旧时光的记忆
6楼-- · 2018-12-31 04:58

the correct way to test floats for 'equality' is:

if(Math.abs(sectionID - currentSectionID) < epsilon)

where epsilon is a very small number like 0.00000001, depending on the desired precision.

查看更多
若你有天会懂
7楼-- · 2018-12-31 04:58

you may want it to be ==, but 123.4444444444443 != 123.4444444444442

查看更多
登录 后发表回答