我试着找出最大的立方根它是一个整数,小于12000。
processing = True
n = 12000
while processing:
n -= 1
if n ** (1/3) == #checks to see if this has decimals or not
我不知道如何检查,如果它是一个整数或不是!我可以将其转换为字符串,然后使用索引来检查结束值,看看它们是否为零,这似乎相当麻烦。有没有更简单的方法?
我试着找出最大的立方根它是一个整数,小于12000。
processing = True
n = 12000
while processing:
n -= 1
if n ** (1/3) == #checks to see if this has decimals or not
我不知道如何检查,如果它是一个整数或不是!我可以将其转换为字符串,然后使用索引来检查结束值,看看它们是否为零,这似乎相当麻烦。有没有更简单的方法?
当前回答
只是一个附加信息,is_integer在内部执行:
import math
isInteger = (math.floor(x) == x)
并不完全是在python中实现的,但cpython实现如上所述。
其他回答
检验立方根不是更简单吗?从20(20**3 = 8000)开始,到30(30**3 = 27000)。然后您必须测试少于10个整数。
for i in range(20, 30):
print("Trying {0}".format(i))
if i ** 3 > 12000:
print("Maximum integral cube root less than 12000: {0}".format(i - 1))
break
>>> 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 (n ** (1.0/3)) % 1 != 0:
print("We have a decimal number here!")
所有的答案都很好,但一个肯定的方法是
def whole (n):
return (n*10)%10==0
如果是整数,函数返回True,否则返回False....我知道我有点晚了,但这是我做的一个有趣的方法。
编辑:正如下面的评论所述,一个更便宜的等效测试将是:
def whole(n):
return n%1==0
你不需要循环或检查任何东西。只要取12000的立方根,四舍五入:
r = int(12000**(1/3.0))
print r*r*r # 10648