简体   繁体   中英

Is it correct to compare denominator == 0.0d to prevent division by zero?

SonarQube has a rule that reports a bug in the following code, stating that " floating point numbers should not be tested for equality ". Generally this rule is justified, but in this case to me it seems to be a false positive. If it is so, I would like to flag it as such, rather than to work around it using constructs with Double.compare , checking intermediate results for +/-Infinity , NaN , or things like that.

public void f(double denominator)
{
    if (denominator == 0.0d)
        throw new IllegalArgumentException("Division by zero.");

    // code that involves division by denominator ...
}

Hence the question: Does the above code throw the IllegalArgumentException if and only if division by denominator (in expressions containing double s only) would lead to +/-Infinity or NaN intermediate values?

We should avoid test float for equality because of the behavior of representing decimals in binary.

The question you asked is essentially, does the above code work? Depending on how f is used, specifically if you are not explicitly passing in 0.0 as the parameter and instead doing something like f((0.4-0.1)-0.3) , it will not catch and divide by a decimal very CLOSE to 0.

PS if you want decimal precision, use BigDecimal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM