Why x and y are not equal? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
4th Sep 2019, 2:33 PM
Sanzid Sadman
Sanzid Sadman - avatar
3 Answers
+ 5
It's simple a double is not a float they are diffrent types try if((float)x==y){};
4th Sep 2019, 4:03 PM
D_Stark
D_Stark - avatar
+ 3
Add this to your code: System.out.println ( x - y); System.out.println (x + y); You'll see you don't get 0 or 6.2. This is because there is a little bit less than what you insert and the difference of what you insert in float is less than double I think or opposite.
4th Sep 2019, 2:54 PM
Eliya Ben Baruch
Eliya Ben Baruch - avatar
+ 2
since the binary hardware representation of decimal numbers is only possible with some error (inaccuracy) that depends on the number of bits used. double x=3.1d; float y=3.1f; String f = "%.16f\n"; System.out.printf(f, x); // 3.1000000000000000 System.out.printf(f, y); // 3.0999999046325684
4th Sep 2019, 9:36 PM
zemiak