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?