浮点比较(1.0 == 1.0)始终为false [英] Float comparison (1.0 == 1.0) always false

查看:86
本文介绍了浮点比较(1.0 == 1.0)始终为false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python 2.7.3和Kivy 1.8.0中使用以下函数来淡入Grid小部件:

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()被无限执行,self.grid.opacity == 1.0始终返回False,因此调度程序从不删除该函数.

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

我以为,文档说,opacity是默认为1.0NumericProperty,但是我正要在调用show()之前更改其值.

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.

这是我尝试过的:

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

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

它不起作用.另外,我确定self.grid.opacity1.0,并且type()在进行比较之前就检索了float.

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

这有效:

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

但是显然我不喜欢这种解决方案.

But obviously I don't like this solution.

有什么想法吗?

推荐答案

正如其他人所说,问题出在浮点数的存储方式上.虽然您可以尝试使用变通办法,但是有一种更好的方法可以做到这一点: Animation .

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.

__init__中:

self.grid.opacity = 0
anim = Animation(opacity=1)
anim.start(self.grid)

这篇关于浮点比较(1.0 == 1.0)始终为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆