gpt4 book ai didi

java - 测试浮点相等性。 (FE_FLOATING_POINT_EQUALITY)

转载 作者:IT老高 更新时间:2023-10-28 20:53:00 35 4
gpt4 key购买 nike

我在 ANT 脚本中使用了 findbugs,但我不知道如何修复我的两个错误。我已阅读文档,但不明白。以下是我的错误以及与之相关的代码:

错误 1:测试浮点相等性。 (FE_FLOATING_POINT_EQUALITY)

private boolean equals(final Quantity other) {
return this.mAmount == convertedAmount(other);
}

错误 2:EQ_COMPARETO_USE_OBJECT_EQUALS

public final int compareTo(final Object other) {
return this.description().compareTo(((Decision) other).description());
}

我已阅读有关 ComparesTo 问题的文档,其中指出

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

还有关于浮点相等的文档

This operation compares two floating point values for equality. Because floating point calculations may involve rounding, calculated float and double values may not be accurate. For values that must be precise, such as monetary values, consider using a fixed-precision type such as BigDecimal. For values that need not be precise, consider comparing for equality within some range, for example: if ( Math.abs(x - y) < .0000001 ). See the Java Language Specification, section 4.2.4.

虽然我不明白。有人可以帮忙吗?

最佳答案

问题一:

对于 FE_FLOATING_POINT_EQUALITY 问题,您不应该将两个浮点值直接与 == 运算符进行比较,因为由于微小的舍入误差,对于您的应用程序而言,这些值可能在语义上“相等”,即使条件 value1 == value2 不成立。

为了解决这个问题,修改你的代码如下:

private boolean equals(final Quantity other) {
return (Math.abs(this.mAmount - convertedAmount(other)) < EPSILON);
}

其中 EPSILON 是您应该在代码中定义的常量,表示您的应用程序可以接受的微小差异,例如.0000001.

问题 2:

对于 EQ_COMPARETO_USE_OBJECT_EQUALS 问题:强烈建议只要 x.compareTo(y) 返回零,x.equals(y) 应为 true。在您的代码中,您已经实现了 compareTo,但您没有覆盖 equals,因此您从 Object< 继承了 equals 的实现,不满足上述条件。

为了解决这个问题,在你的类中重写 equals(也许还有 hashCode),这样当 x.compareTo(y)返回 0,然后 x.equals(y) 将返回 true

关于java - 测试浮点相等性。 (FE_FLOATING_POINT_EQUALITY),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3832592/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com