+ 5
Python
dose anybody know why this code gives False answer ???? print(0.1 + 0.2 == 0.3)
8 odpowiedzi
+ 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
+ 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
+ 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.
+ 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
+ 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
+ 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 :)
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
0
1. ==
2. +