2

I heard that floating point arithmetic like 0.1 + 0.2 may yield rounding error like 0.30000000000000004 due to binary floating point being used internally.

But if I add a 0 to any floating point number in C++, does it guarantee to produce the same value without any rounding error? I have no idea how floating point arithmetic works and when rounding error appears.

JavaMan
  • 4,954
  • 4
  • 41
  • 69
  • An exact zero (positive or negative) should not cause trouble for most implementations of floating point, as non-NaN values shall be preserved (no rounding issues). Powers of 2 are also exactly represented. – Paul Stelian Jul 18 '16 at 08:52
  • 0.1 and 0.2 cannot be represented exactly as they are not powers of 2 or finite sums thereof (a sum of powers of 2 is representable in the usual 32-bit float format if the difference between the powers is at most 22 (between largest and smallest) – Paul Stelian Jul 18 '16 at 08:53
  • [For any finite floating point value, is it guaranteed that x - x == 0?](http://stackoverflow.com/q/3599579/995714), https://randomascii.wordpress.com/2013/07/16/floating-point-determinism/, http://stackoverflow.com/q/10791894/995714 – phuclv Jul 18 '16 at 09:53

1 Answers1

1

If the C++ implementation supports IEEE754 math, then it is guaranteed. The IEEE754 standard has precise definitions of mathematical operations, so C++ doesn't define its own rules. But IEEE754 support is not mandatory.

x + 0.0 == x is true for any number (*) because IEEE754 guarantees that addition, subtraction, multiplication and division are precise to the last bit.

(*) When x is Not a Number (NaN), x+0.0 is also NaN, but NaN != NaN in IEEE754.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • are there any non-IEEE754 implementations out there? Is it practically determined by the processor (math coprocessor) alone? – JavaMan Jul 26 '16 at 07:06
  • @JavaMan: Quite a few compilers can do "unsafe" optimizations which violate IEEE754. Classic example `(a*a*a*a*a*a)` isn't `(a*a*a)*(a*a*a)`. So it's not just the processor. – MSalters Jul 26 '16 at 07:33