1

I understand that doing math with floats can be strange because the float cannot always be expressed in binary correctly and then converted back. However, the following code contains the same simple equation 3 "different" ways. I say "different" because it's the same equation in the same order and everything but just typed in a different style. If it's doing the same conversion from float to binary and back to float to be displayed then how can it be different? Here is the c++ code:

#include <iostream>

using namespace std;

int main() {
    // using literal numbers
    cout << 0.1 + 0.1 + 0.1 - 0.3 << endl;

    float f_one = 0.1;
    float f_three = 0.3;

    // using floats
    cout << f_one + f_one + f_one - f_three << endl;

    double d_one = 0.1;
    double d_three = 0.3;

    // using doubles
    cout << d_one + d_one + d_one - d_three << endl;

    return 0;
}

The output of this code is

5.55112e-017
-7.45058e-009
2.77556e-017

I can understand that there can be a difference between float and double, that was expected. But shouldn't at least one of the two match the result obtained by

cout << 0.1 + 0.1 + 0.1 - 0.3 << endl;

?

What else could be causing this difference?

nal
  • 11
  • 1
  • Floating point arithmetic in an approximation by design, think about how small is a `10^-17`. – Jack Jan 21 '19 at 04:38
  • Interesting, with gcc 7.3.0 I get `5.55112e-17 0 5.55112e-17`. Which compiler did you use? – Kingsley Jan 21 '19 at 04:40
  • Conventionally, we represent fractional numbers in base 10. Most of these can only be approximated by binary which is what CPUs use. This is often surprising. – doug Jan 21 '19 at 04:55
  • @Kingsley I'm using GCC 6.3.0 on Windows if that makes a difference. Very strange but I'm sure there is a good reason. – nal Jan 22 '19 at 21:01

0 Answers0