Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a double is zero?

Tags:

java

I have some code like this:

class Foo {     public double x; }  void test() {     Foo foo = new Foo();      // Is this a valid way to test for zero? 'x' hasn't been set to anything yet.     if (foo.x == 0) {      }      foo.x = 0.0;      // Will the same test be valid?     if (foo.x == 0) {      } } 

I basically want to avoid a divide-by-zero exception in the future.

Thanks

like image 381
user291701 Avatar asked Aug 15 '13 19:08

user291701


People also ask

Can you compare double with zero?

I think as long as the number has an exact binary fraction representation (like 0) the comparison is perfectly valid. Show activity on this post. You should not use double for such comparision. double creates problem.

Can you use == to compare doubles?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.

How do you check for doubles equality?

equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same.


1 Answers

Numeric primitives in class scope are initialized to zero when not explicitly initialized.

Numeric primitives in local scope (variables in methods) must be explicitly initialized.

If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.

if(value != 0)     //divide by value is safe when value is not exactly zero. 

Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.

public boolean isZero(double value, double threshold){     return value >= -threshold && value <= threshold; } 
like image 83
William Morrison Avatar answered Sep 21 '22 02:09

William Morrison