Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we say that it's always true that 0.5*x + 0.5*x == x?

0.5 is a (negative) power of 2, which means it is exactly representable by the IEEE-754 binary floating-point format. In signle precision it is 0'01111110'00000000000000000000000.

Based on my quick tests with optimizations turned off (-O0), it turns out that if y = 0.5 * x, then y + y == x. But is it always guaranteed by the IEEE-754 standard?

I know that in general if n is a positive integer power of 2, and m = 1.0 / n, y = m * x, then adding y together n times doesn't produce x. But it seems that with n = 2 yes.

Do I miss something?

like image 886
plasmacel Avatar asked Mar 09 '23 21:03

plasmacel


1 Answers

No, here is a trivial counter example with double precision floating points:

double x = 4.9E-324; // minimum positive value
double y = x * 0.5; // this doesn't only look like a zero this positive zero all 0 bits
bool test = y + y == x; // false

Floating-point numbers under IEEE-754 have limited precision, and we can lose information when dividing by 2. In most cases when making the number smaller you gain accuracy, you can decrease the exponent, but as above this isn't always enough. Sometimes you can't decrease the exponent.

Anything with minimal exponent and odd mantissa will not hold the equality. Such an example is x = 5.0E-322.

like image 119
Meir Maor Avatar answered Mar 27 '23 06:03

Meir Maor