+ 6
Why the comparison of float and double (C++) are not equal?
* Why is the comparison of 2.0 the same and when comparing 2.3 is different? * Why, if they are all 2.5 in one case, do I give the same and the other one different? main() { float a = 2.0, x = 2.3; double b = 2.0, y = 2.3 cout << (a == b) << (x == y); a += 0.5; b += 0.5; x += 0.1; x += 0.1; y += 0.1; y += 0.1; cout << (a == b) << (x == y); return 0; } #output: 1010 https://code.sololearn.com/c09wmaN5lwL0/?ref=app
6 odpowiedzi
+ 6
One could say that the comparison of a float and a double is uncertain. It should never have been!"
+ 6
I can understand that the comparison of 2.0 is the same and 2.3 different, but I do not understand why 2.5 in one case is the same and in the other different.. someone could explain it please
+ 6
And in this case the reason is the same or there is another reason .. since the variables are of the same type
float a = 2.0, b = 2.3;
a += 0.5;
b += 0.1;
b += 0.1;
cout << (a == b);
#output : 0
https://code.sololearn.com/c3Q9D7G9kb7u/?ref=app
+ 5
Just to add something to kurwius answer:
If you really want to compare floating point values you could do something like (abs(x-y) < 0.0001)
But never ever use == for float or double!
You can test something in your code if you want. just add it to your code
#include <iomanip>
cout << setprecision(17); //in main
and then output your different values. you'll see the difference
+ 5
Because they are both not exactly 2.5
Double a bit more exactly than float, but still not exactly 2.5
Maybe this helps your understanding:
https://code.sololearn.com/cWoz56yHO4M3/?ref=app
+ 2
Good thing that you really want to know why things do what they do.
To fully understand it I would recommend you to look up how the conversion from decimal to binary floating point values are calculated.
Google "decimal to floating point conversion"
I'll just give a short explanation:
IEEE-754 defines that a floating point value consists of 3 elements: sign, exponent, mantissa.
For 32-bit numbers (-> float):
1 bit -> sign (positive = 0, negative = 1)
8 bit -> exponent
24 bit -> mantissa
I won't explain the converting process itself, but will give you 2 examples:
0.5 in floating point:
sign = 0
exp. = 01111110
mantissa = 000.....000 (23*0)
0.1 in floating point:
sign: 0
exp. = 01111011
mantissa = 10011001100110011001101
you can see that it's a pattern in the mantissa
1001 1001 1001 and so on.
This means that the number is no exact value, but a approximation that gets more and more accurate the more bits you give it. (that's the reason why double has a higher precision).
tl,dr: Most number represented in float are just approximations