Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If double a=0.0, can I compare a*b==0 directly?

Tags:

java

double

I know double should not be compared by == operator directly, but how about if I define an initial value as 0.0?eg:

double a=0.0;
double b=
.
.
.

If a is not modified, does a*b==0 always true?

like image 812
Gstestso Avatar asked Aug 24 '16 05:08

Gstestso


1 Answers

I know double should not be compared by == operator direct

That is only true if you don't know how much representation or rounding error you have. A classic example of what not to do is

0.1 + 0.2 == 0.3 // false :(

However, if you use rounding like

if (round4(0.1 + 0.2) == 0.3) // true

from Chronicle Core's Maths

public static double round4(double d) {
    final double factor = 1e4;
    return d > WHOLE_NUMBER / factor || d < -WHOLE_NUMBER / factor ? d :
            (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}

If a is not modified, does a*b==0 always true?

It is for finite numbers. For infinity and NaN you will get NaN and this is not equal to anything.

like image 129
Peter Lawrey Avatar answered Oct 13 '22 01:10

Peter Lawrey