Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

python - Float comparison (1.0 == 1.0) always false

I'm using the following function in Python 2.7.3 and Kivy 1.8.0 to fade-in a Grid widget:

def __init__(self, **kwargs):
     # ...Init parent class here...
     self.grid.opacity = 0.0
     Clock.schedule_interval(self.show, 1 / 10)

def show(self, value):
    if self.grid.opacity == 1.0:
        return False
    else:
        self.grid.opacity += 0.1

show() is executed infinitely, self.grid.opacity == 1.0 always returs False, so the scheduler never removes the function.

I thought, and the documentation says, that opacity is a NumericProperty which defaults to 1.0, but I'm changing its value right before show() is called.

This is what I've tried:

if self.grid.opacity == NumericProperty(1.0):

if float(self.grid.opacity) == 1.0:

It doesn't work. Also, I'm sure self.grid.opacity is 1.0 and type() retrieves float right before I make the comparison.

This works:

if str(self.grid.opacity) == "1.0":

But obviously I don't like this solution.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...