python - 如何检查浮点值是否为整数

标签 python floating-point

我试图找到小于 12,000 的整数的最大立方根。

processing = True
n = 12000
while processing:
    n -= 1
    if n ** (1/3) == #checks to see if this has decimals or not

虽然我不确定如何检查它是否是整数!我可以将它转换为字符串,然后使用索引来检查最终值并查看它们是否为零,但这看起来相当麻烦。有没有更简单的方法?

最佳答案

要检查浮点值是否为整数,请使用 float.is_integer() method :

>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False

该方法已添加到 float输入 Python 2.6。

考虑到在 Python 2 中,1/30 (整数操作数的底除法!),并且浮点运算可能不精确(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)

关于python - 如何检查浮点值是否为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49847677/

相关文章:

c# - .NET 的 Double.ToString 方法中的两次错误

python - Python 和 Selenium : authenticate against Active Directory 的解决方法

floating-point - PROLOG - 如何舍入 float 的小数?

c++ - 如何在现代 C++ 中将 float 转换为 int

python - python 警告的日志堆栈跟踪

c# - C# 中的 float 是否有一个好的基数排序实现

c - 在 C 中存储和处理具有 1,000,000 位有效数字的 float 的最有效方法是什么?

python - 为什么对称矩阵的Numpy特征向量无法构造原始矩阵

python - SQLAlchemy:覆盖查询中关系定义的 "order_by"

python - 将类似范围的序列连接到元组列表