I have messed with code execution result.
code:
System.out.println(0.2==0.1+0.1);
System.out.println(0.3==0.1+0.1+0.1);
output:
true
false
I know that 0.2 and 0.3 cannot transform to binary correct.
Why do I see different results?
UPDATE:
Can I predict result in similar issues without compiler?
System.out.println(0.1+0.1+0.1);
output
0.30000000000000004
There is a rounding error on floating point arithmetics. Some values are can not be represented in base 2, you can't rely on comparing float numbers. 0.1 in base-2 is like 1/3 in base-10.
You can see the link below
What Every Computer Scientist Should Know About Floating-Point Arithmetic
What you see is the fact that floating point values are not very accurate and you should not for example compare them using ==
operator. For comparisons you should use epsilon compares, ie. for two floating point values f1 and f2
if (Math.abs(f1 - f2) < EPSILON ) {
// they are equal
}
Where EPSILON is some very small floating point value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With