为 Java class 创建 equal 方法来比较 double 或 int 值
create equal method for Java class to compare double or int values
我的作业是创建一个 class 的 equal 方法,该方法覆盖对象 class 在 Java 中的 equal 方法。我的编码如下,但讲师评论说:"doubles cannot be compared for equality with ==,!= as storage is not exact." 那么在这种情况下我该如何相应地编辑代码呢?非常感谢你。
class 游戏设置 {
private int firingInterval;
private double moveSpeed;
...
public boolean equals(Object obj) {
//objects are equal if same firingInterval and moveSpeed
GameSettings other;
boolean result = false;
//TODO
other = (GameSettings) obj;
if (obj instanceof GameSettings) {
return (firingInterval == other.getFiringInterval()
&& moveSpeed == other.getMoveSpeed());
} else {
return result;
}
}
正如您的讲师所说,比较double并不仅仅使用等于运算符。例如,您可以尝试 1 不等于 1.000。
相反,我们经常使用两个值之间的增量来比较双精度值。如果增量相对较小,那么这些值将相等。
public static final double EPSILON = 0.0000000001;
public boolean compare(double a, double b) {
return Math.abs(a-b) < EPSILON;
}
我的作业是创建一个 class 的 equal 方法,该方法覆盖对象 class 在 Java 中的 equal 方法。我的编码如下,但讲师评论说:"doubles cannot be compared for equality with ==,!= as storage is not exact." 那么在这种情况下我该如何相应地编辑代码呢?非常感谢你。 class 游戏设置 {
private int firingInterval;
private double moveSpeed;
...
public boolean equals(Object obj) {
//objects are equal if same firingInterval and moveSpeed
GameSettings other;
boolean result = false;
//TODO
other = (GameSettings) obj;
if (obj instanceof GameSettings) {
return (firingInterval == other.getFiringInterval()
&& moveSpeed == other.getMoveSpeed());
} else {
return result;
}
}
正如您的讲师所说,比较double并不仅仅使用等于运算符。例如,您可以尝试 1 不等于 1.000。
相反,我们经常使用两个值之间的增量来比较双精度值。如果增量相对较小,那么这些值将相等。
public static final double EPSILON = 0.0000000001;
public boolean compare(double a, double b) {
return Math.abs(a-b) < EPSILON;
}