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

I know that double should not be compared directly with the == operator, but what about determining the initial value as 0.0? eg:

double a=0.0; double b= . . . 

If a is not changed, does * b == 0 always matter?

+5
source share
2 answers

I know double should not be compared with operator operator

This is only true if you do not know how many representation or rounding errors you have. A classic example of what you don't need to do is

 0.1 + 0.2 == 0.3 // false :( 

However, if you use rounding, for example

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

from Chronicle of the core Mathematics

 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 changed, does * b == 0 always matter?

This is for finite numbers. For infinity and NaN you get NaN , and that doesn't mean anything.

+4
source

Multiplying with 0.0 will result in 0.0 (for sure, without rounding errors or other inaccuracies - unless things like infinity or NaN are involved).

But if you end up with 0.0 or something close to 0.0 after arbitrary operations, you cannot be sure if this is (mathematically) 0 and use epsilon.

+4
source

All Articles