让我们考虑下面的代码
代码:
#!/usr/bin/env python
class Foo():
def __init__(self, b):
self.a = 0.0
self.b = b
def count_a(self):
self.a += 0.1
foo = Foo(1)
for i in range(0, 15):
foo.count_a()
print "a =", foo.a, "b =", foo.b, '"a == b" ->', foo.a == foo.b
输出:
a = 0.2 b = 1 "a == b" -> False
a = 0.4 b = 1 "a == b" -> False
a = 0.6 b = 1 "a == b" -> False
a = 0.8 b = 1 "a == b" -> False
a = 1.0 b = 1 "a == b" -> True
a = 1.2 b = 1 "a == b" -> False
a = 1.4 b = 1 "a == b" -> False
a = 1.6 b = 1 "a == b" -> False
a = 1.8 b = 1 "a == b" -> False
a = 2.0 b = 1 "a == b" -> False
a = 2.2 b = 1 "a == b" -> False
a = 2.4 b = 1 "a == b" -> False
a = 2.6 b = 1 "a == b" -> False
a = 2.8 b = 1 "a == b" -> False
a = 3.0 b = 1 "a == b" -> False
但是,如果我将11
行上的代码更改为foo = Foo(2)
,输出将变为:
a = 0.2 b = 2 "a == b" -> False
a = 0.4 b = 2 "a == b" -> False
a = 0.6 b = 2 "a == b" -> False
a = 0.8 b = 2 "a == b" -> False
a = 1.0 b = 2 "a == b" -> False
a = 1.2 b = 2 "a == b" -> False
a = 1.4 b = 2 "a == b" -> False
a = 1.6 b = 2 "a == b" -> False
a = 1.8 b = 2 "a == b" -> False
a = 2.0 b = 2 "a == b" -> False *
a = 2.2 b = 2 "a == b" -> False
a = 2.4 b = 2 "a == b" -> False
a = 2.6 b = 2 "a == b" -> False
a = 2.8 b = 2 "a == b" -> False
a = 3.0 b = 2 "a == b" -> False
您将看到输出a = 2.0 b = 2 "a == b" -> False
完全是怪异的。我想我可能误解了Python中OOP的一些概念。请向我解释为什么会出现这种意外输出,以及如何解决这个问题。
这与对象定向无关,而是与计算机内部表示浮点数的方式以及舍入误差有关。http://floating-point-gui.de/basic/
Python的特殊性是浮点数字的默认字符串表示,与内部表示相比,浮点数字将以更少的小数位数进行四舍五入,以进行漂亮的打印。
尽管对于需要正确比较的人来说,考虑到浮点数的小数位数,Python已经引入了一个很好的机制PEP485,它将math.isclose
函数添加到了标准库中。
除了jsbueno的正确解释外,请记住Python通常允许将"基本类型"转换为自己。
即str("a")=="a"
因此,如果除此之外还需要一个变通方法,只需将int/foat混合转换为所有浮点并测试它们即可。
a = 2.0
b = 2
print "a == b", float(a) == float(b)
输出:
a == b True