What is the result of the following code execution?

System.out.println( 0.3 == 0.1d + 0.1d + 0.1d );
Explanation
The correct answer to this question is related to the method of representation of fractional numbers in the computer memory. They are stored in a binary representation.

If we try to convert 0.1 into the binary system, we will obtain an infinite binary fraction 0.000110011001100110011001100 ... Since a number in a computer's memory is represented by a finite number of bits (for example, 64 bits are allocated to values of type double), then an infinite binary fraction is simply rounded. Rounded number will differ a little bit from the original one. Similarly, the binary representation of 0.3 will slightly differ from the actual value of 0.3.
It turns out that in the example two numbers, each of which is approximately equal to 0.3, are compared, but they are not equal to each other.
If we take numbers with another binary representation, we will obtain a different result. For example, System.out.println( 0.375 == 0.125d + 0.125d + 0.125d ) results in true.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести