Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to compare a double to zero if you previously initialized it to zero?

I learnt that comparing a double using == is not a wise practice. However I was wondering if checking if a double has been initialized could be dangerous or not. For example, knowing that a variable doubleVar cannot be zero if it has been initialized, is it safe to do this?

Foo::Foo(){
    doubleVar = 0.0;  // of type double
}

void Foo::Bar(){
    if(doubleVar == 0){ // has been initialized?
        //...
    }else{
        //...
    }
}
like image 991
HAL9000 Avatar asked Jan 28 '14 20:01

HAL9000


1 Answers

In IEEE-754, long story short:

double d;

d = 0.0;
d == 0.0   // guaranteed to evaluate to true, 0.0 can be represented exactly in double

but

double d;

d = 0.1;
d == 0.1   // not guaranteed to evaluate to true
like image 100
ouah Avatar answered Oct 13 '22 06:10

ouah