Reputation: 1
Why does this statement return false? When I calculate it by hand I get 114 = 114 which should be true:
System.out.println(114 == (114.0 / Math.PI * Math.PI));
Upvotes: 0
Views: 60
Reputation: 685
Because
System.out.println(114.0 / Math.PI * Math.PI);
will print
114.00000000000001
You can try
System.out.println(114 == (int)(114.0 / Math.PI * Math.PI));
(converting the float to int)This will return true...
Upvotes: 0
Reputation: 21961
Try with following code:
double res=114.0 / Math.PI * Math.PI;
System.out.println(res);
Result is: 114.00000000000001 not 114.
Upvotes: 1
Reputation: 16987
That's because by using Math.PI
you introduce floating point arithmetic, which is not as precise as actual integer arithmetic. The result of the right side will in fact 114.00000000000001, a value that is very very very close to 114, but not exactly.
Upvotes: 2