Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Floating point zero comparison

Will the following code, with nothing in between the lines, always produce a value of true for the boolean b?

double d = 0.0;
bool b = (d == 0.0);

I'm using g++ version 4.8.1.

like image 570
Amandeep Grewal Avatar asked Feb 15 '23 11:02

Amandeep Grewal


1 Answers

Assuming IEEE-754 (and probably most floating point representations), this is correct as 0.0 is representable exactly in all IEEE-754 formats.

Now if we take another literal that is not representable exactly in IEEE-754 binary formats, like 0.1:

double d = 0.1;
bool b = (d == 0.1);

This may result in false value in b object!

The implementation has the right to use for example a double precision for d and a greater precision for the comparison with the literal.

(C99, 5.2.4.2.2p8) "Except for assignment and cast (which remove all extra range and precision), the values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type."

like image 153
ouah Avatar answered Feb 23 '23 12:02

ouah