问题描述
在JBox2d中,存在以下代码: Vec2.equals()
: @Override
public boolean equals(Object obj){//由Eclipse自动生成
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass()!= obj.getClass())
return false;
Vec2 other =(Vec2)obj;
if(Float.floatToIntBits(x)!= Float.floatToIntBits(other.x))
return false;
if(Float.floatToIntBits(y)!= Float.floatToIntBits(other.y))
return false;
返回true;
}
我想知道float int - 这里。这是否提供了解决Java的浮点比较不准确问题的方法(如果可能的话)?还是完全是另一回事?我想知道,如果这是一个替代的epsilon方法:
if(Math.abs(floatVal1 - floatVal2)< epsilon )
PS。为了完整性和利益,这里是 Vec2.hashCode()
:
@Override
public int hashCode(){//由Eclipse自动生成
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
返回结果;
$ b $ p
$ b $ p $ { - 散列ID必须是整数。解决方案可以在: float
和<$ c $因为存在 -0.0
, NaN
,所以需要特殊的处理无限,负无穷。这就是为什么Sun JVM的 Float.equals()
看起来像这样(6u21):
public boolean equals(Object obj)
{
return(obj instanceof Float)
&& (floatToIntBits(((Float)obj).value)== floatToIntBits(value)); (
$所以,不, Math.abs()
与epsilon不是一个好的选择。从Javadoc:
$ b 这就是为什么Eclipse的自动生成的代码为你做的。
In JBox2d, there exists the following code for Vec2.equals()
:
@Override
public boolean equals(Object obj) { //automatically generated by Eclipse
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vec2 other = (Vec2) obj;
if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x))
return false;
if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y))
return false;
return true;
}
I am wondering what purpose the float<->int bit conversions functions serve, here. Does this provide a way to get around Java's float comparison inaccuracy problem (if such is even possible)? Or is it something else altogether? I am wondering if it is an alternative to the epsilon approach:
if (Math.abs(floatVal1 - floatVal2) < epsilon)
PS. for the sake of completeness and interest, here is Vec2.hashCode()
:
@Override
public int hashCode() { //automatically generated by Eclipse
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
return result;
}
FYI, I can see perfectly why the conversion functions are used in hashCode() -- hash IDs must be integers.
解决方案 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:
That's why Eclipse's autogenerated code does that for you.
这篇关于为什么在Java float比较中使用Float.floatToIntBits()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!