4

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?

plasmacel
  • 8,183
  • 7
  • 53
  • 101
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – mehulmpt Jun 10 '17 at 06:00
  • 5
    @mehulmpt That question is about `0.2 + 0.1 != 0.3`, which since `0.2` and `0.1` are not exactly representable by any binary floating-point format is totally obvious. I think you don't understand the difference here. – plasmacel Jun 10 '17 at 06:02

1 Answers1

7

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.

plasmacel
  • 8,183
  • 7
  • 53
  • 101
Meir Maor
  • 1,200
  • 8
  • 18