Why is output of this code "false": 0.1 + 0.2 == 0.3 | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

Why is output of this code "false": 0.1 + 0.2 == 0.3

31st Jul 2018, 7:43 AM
Adeolu F
Adeolu F - avatar
5 ответов
+ 3
== stands for the equality operator, this checks if the value on the left-hand side is equal to the one on the right. Since computers are not really quite accurate when it comes to decimals, adding 0.1 to 0.2 would not equal to 0.3, actually the output would be 3.0000000000000004 due to something called 'floating-point imprecision'. Notice the inequality? That's why the output is 'False'!
31st Jul 2018, 8:19 AM
apex137
apex137 - avatar
+ 4
one more note...binary can represent all integers accurately. so I have always been taught to merely convert inputs to integers first then do calculations which will be accurate without the trailing remainders that go on forever. then convert final answer back to decimal. works great for adding, multiplying, and subtracting quantities, percentages, and dollars and cents.
31st Jul 2018, 11:59 AM
Lisa F
Lisa F - avatar
+ 3
the underlying reason for the problem is that binary, the base language of the computer cannot represent decimal .1 perfectly just like our decimal system cannot represent 1/3 perfectly. decimal .333333333 goes on forever. such is the case when you write 0.1 in binary. it is something like 0.00011001100110011 with the last four digits going on forever. eventually the programming language cuts it off having only so many bits to store a floating point number and that's where the last digit, the 4 comes from in the preferred answer...those final digits being added together. https://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/ for more information.
31st Jul 2018, 11:53 AM
Lisa F
Lisa F - avatar
0
James Depending on the situation this is even worse. With int everything will be converted to 0 in this example. But if you have e.g. 0.4 + 0. 7 and convert all to int you would have 0 + 0 == 1 which is obviously false. When comparing two floats to be "equal", rather substract it with the result, take the absolute value and compare it to a small number, like 1e-15 or so. Depending on the accuracy you want/expect to achieve. So 0.1 + 0.2 == 0.3 in computer language is the "same" as abs(0.1+0.2 - 0.3) < 1e-15 The latter is more robust against floating point errors. In machine precision zero is the same as a very small number.
31st Jul 2018, 10:16 AM
Matthias
Matthias - avatar
0
Then you could also remove any code and just type True by yourself ;) There are beginners here and might think this actually solves the problem for any such situation.
31st Jul 2018, 10:22 AM
Matthias
Matthias - avatar