为什么is_integer()方法不起作用?

cha*_*ghe 1 python floating-point python-2.7

我用Python编写了这段代码:

x=345**3
z=float(x)**(1.0/3.0)
print z
print z.is_integer()
Run Code Online (Sandbox Code Playgroud)

输出是:

345.0
False
Run Code Online (Sandbox Code Playgroud)

这是为什么?我期待输出True.

jon*_*rpe 6

因为z不完全是345.0:

>>> x = 345 ** 3
>>> z = float(x) ** (1.0 / 3.0)
>>> print z
345.0
>>> (345.0).is_integer()
True
Run Code Online (Sandbox Code Playgroud)

然而到目前为止一切都很好:

>>> z.is_integer()
False
>>> z == 345.0
False
>>> z
344.9999999999999
Run Code Online (Sandbox Code Playgroud)

由于以下方面的不同strrepr形式,这只是一个显示问题float:

>>> z.__repr__()
'344.9999999999999'
>>> z.__str__()
'345.0'
Run Code Online (Sandbox Code Playgroud)