+ 5

Python

dose anybody know why this code gives False answer ???? print(0.1 + 0.2 == 0.3)

25th Aug 2021, 2:34 PM
Pouya Haji Mohammadi Gohari
Pouya Haji Mohammadi Gohari - avatar
8 ответов
+ 14
Because those numbers cannot be exactly rappresented as a binary floating point The nearest rappresentations are: 0.1 -> 0.10000000000000000 0.2 -> 0.20000000000000001 0.1 + 0.2 -> 0.30000000000000004 0.3 -> 0.29999999999999998
25th Aug 2021, 2:58 PM
Angelo
Angelo - avatar
+ 10
I wouldn't call myself an expert, but what we observe here is a limit of floating point precision. This does not apply only to python but to other programming languages as well. It has to do with how data are stored at machine level. So it is not a "bug" that 0.1 + 0.2 is not equal to 0.3. Generally "==" comparisons will be impractical/ uninformative for floats and should be avoided. https://docs.python.org/3/tutorial/floatingpoint.html
25th Aug 2021, 2:58 PM
Lisa
Lisa - avatar
+ 4
You shouldn't compare floating point values with relational operators. In some languages, floating point numbers are converted to their fraction equivalents then compared. Maybe you should take a similar approach by multiplying the numbers to be compared by their precision aka if it's 0.2 multiply by 10, convert to an int then compare.
25th Aug 2021, 3:28 PM
Segmentation Fault
Segmentation Fault - avatar
+ 2
Pouya Haji Mohammadi Gohari Yes, i can see you changed it. I see what you mean🤔 I dont know why it adds funny 0.1 + 0.2 = 0.30000000000000004 We need a python expert https://code.sololearn.com/cWr5vF3j8QW2/?ref=app
25th Aug 2021, 2:48 PM
Brain & Bones
Brain & Bones - avatar
+ 2
Hi Pouya! I found these resources on Internet. Most of the people explained the concept clearly. Hope these help you https://stackoverflow.com/questions/62727051/is-0-1-0-2-0-3-true-or-false https://www.quora.com/What-is-the-output-of-print-0-1+0-2-0-3
25th Aug 2021, 3:18 PM
Python Learner
Python Learner - avatar
+ 1
What's dumb about it? Concerning binary representation it makes perfect sense. Apart from that, there is this saying, that a computer is only as smart as its user :)
27th Aug 2021, 8:03 AM
Lisa
Lisa - avatar
0
Pouya Haji Mohammadi Gohari How about using the 'approximate' function for your needs? :- approximate = lambda flt: float(f"{flt:.16f}") print(approximate(0.1 + 0.2) == 0.3) # Just a crude way
26th Aug 2021, 6:30 AM
Calvin Thomas
Calvin Thomas - avatar
0
1. == 2. +
26th Aug 2021, 8:52 AM
Максим Вахитов
Максим Вахитов - avatar