我试着找出最大的立方根它是一个整数,小于12000。

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

我不知道如何检查,如果它是一个整数或不是!我可以将其转换为字符串,然后使用索引来检查结束值,看看它们是否为零,这似乎相当麻烦。有没有更简单的方法?


当前回答

上述答案适用于许多情况,但也有遗漏。考虑以下几点:

fl = sum([0.1]*10)  # this is 0.9999999999999999, but we want to say it IS an int

以此为基准,其他一些建议并没有得到我们想要的行为:

fl.is_integer() # False

fl % 1 == 0     # False

而不是尝试:

def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

def is_integer(fl):
    return isclose(fl, round(fl))

现在我们得到:

is_integer(fl)   # True

isclose随Python 3.5+附带,对于其他Python,您可以使用这个基本等效的定义(如相应的PEP中所述)

其他回答

你可以用模运算。

if (n ** (1.0/3)) % 1 != 0:
    print("We have a decimal number here!")

上述答案适用于许多情况,但也有遗漏。考虑以下几点:

fl = sum([0.1]*10)  # this is 0.9999999999999999, but we want to say it IS an int

以此为基准,其他一些建议并没有得到我们想要的行为:

fl.is_integer() # False

fl % 1 == 0     # False

而不是尝试:

def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

def is_integer(fl):
    return isclose(fl, round(fl))

现在我们得到:

is_integer(fl)   # True

isclose随Python 3.5+附带,对于其他Python,您可以使用这个基本等效的定义(如相应的PEP中所述)

>>> def is_near_integer(n, precision=8, get_integer=False):
...     if get_integer:
...         return int(round(n, precision))
...     else:
...         return round(n) == round(n, precision)
...
>>> print(is_near_integer(10648 ** (1.0/3)))
True
>>> print(is_near_integer(10648 ** (1.0/3), get_integer=True))
22
>>> for i in [4.9, 5.1, 4.99, 5.01, 4.999, 5.001, 4.9999, 5.0001, 4.99999, 5.000
01, 4.999999, 5.000001]:
...     print(i, is_near_integer(i, 4))
...
4.9 False
5.1 False
4.99 False
5.01 False
4.999 False
5.001 False
4.9999 False
5.0001 False
4.99999 True
5.00001 True
4.999999 True
5.000001 True
>>>

你可以用这个:

if k == int(k):
    print(str(k) + " is a whole number!")

所有的答案都很好,但一个肯定的方法是

def whole (n):
     return (n*10)%10==0

如果是整数,函数返回True,否则返回False....我知道我有点晚了,但这是我做的一个有趣的方法。

编辑:正如下面的评论所述,一个更便宜的等效测试将是:

def whole(n):
    return n%1==0