Float Comparison (1.0 == 1.0) Always False
Solution 1:
It is probably not Python specific. Read What Every Programmer Should Know About Floating-Point Arithmetic.
0.1 is not exactly representable as a IEEE754 double-precision floating point. So I guess that the floating point (parsed from) 0.1
(which is not exactly one tenth) is not converted as a string "0.1"
Solution 2:
Might be a float comparison issue. I don't know the application, but float's are never exact, so testing them for equality can cause problems. You can try something like:
ifabs(float(self.grid.opacity) - 1.0) < .001:
pass
An example of funny float behavior, at least on my setup:
>>> .1 + .1 + .1 == .3False>>> .1 + .1 == .2True
Solution 3:
This is your problem:
>>>q=0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1>>>str(q)
'1.0'
>>>q
0.9999999999999999
>>>q==1
False
Bottom line never compare floats with ==, period.
Solution 4:
As others have stated, the problem is due to the way floating point numbers are stored. While you could try to use workarounds, there's a better way to do this: Animation
.
In __init__
:
self.grid.opacity = 0
anim = Animation(opacity=1)
anim.start(self.grid)
Solution 5:
@Basile Starynkevitch answers why this is happening, the nature of floating point numbers is at work here. The general form for doing this kind of comparison is:
abs(numberA - numberB) <= SOMEEPSILON
where SOMEEPSILON
is a number you deem to be an acceptable margin.
If you're working with smaller numbers and not worried about a rounding error you can sys.float_info.epsilon
So as I commented by combining the two you get:
abs(self.grid.opacity- 1.0) <= sys.float_info.epsilon
The definition of epsilon's value in the docs is:
difference between 1 and the least value greater than 1 that is representable as a float
Which is a another way of saying, the smallest value between 1 and the number right before it.
So for example, if python could only represent numbers up to 2 decimal places, epsilon would be the difference between 1.00 and 0.99 (in reality the value is much smaller than that)
Post a Comment for "Float Comparison (1.0 == 1.0) Always False"