Why use Float.floatToIntBits() in Java float comparisons?

a 夏天 提交于 2019-11-29 01:18:46

The explanation can be found in Joshua Bloch's Effective Java: float and Float need special treatment because of the existence of -0.0, NaN, positive infinity, and negative infinity. That's why the Sun JVM's Float.equals() looks like this (6u21):

public boolean equals(Object obj)
{
    return (obj instanceof Float)
           && (floatToIntBits(((Float)obj).value) == floatToIntBits(value));
}

So, no, Math.abs() with an epsilon is not a good alternative. From the Javadoc:

If f1 and f2 both represent Float.NaN, then the equals method returns true, even though Float.NaN==Float.NaN has the value false. If f1 represents +0.0f while f2 represents -0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has the value true.

That's why Eclipse's autogenerated code does that for you.

Double.Nan (Not-a-number) is a special value when it comes to comparison:

System.out.println(Float.NaN == Float.NaN);
System.out.println(Float.floatToIntBits(Float.NaN) == Float.floatToIntBits(Float.NaN));

This prints:

false
true 

I do not know 100%, but most probably they are trying to get around the NaN != NaN problem. If your float happens to be NaN you cannot compare to anything as the result is always false. Comparing the intBits will give you NaN == NaN.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!