要检查浮点值是否为整数,请使用float.is_integer() method:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
该方法在 Python 2.6 中被添加到 float 类型中。
考虑到在 Python 2 中,1/3 是 0(整数操作数的下除法!),并且浮点运算可能不精确(float 是使用二进制分数的近似值,不是一个精确的实数)。但是稍微调整一下你的循环会给出:
>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
这意味着任何超过 3 的立方(包括 10648)由于上述不精确性而被遗漏:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
您必须检查与整数接近的数字,或者不使用float() 来查找您的号码。就像向下取整 12000 的立方根:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
如果您使用的是 Python 3.5 或更高版本,则可以使用 math.isclose() function 查看浮点值是否在可配置的边距内:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
对于旧版本,该函数的幼稚实现(跳过错误检查并忽略无穷大和 NaN)为 mentioned in PEP485:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)