我试着找出最大的立方根它是一个整数,小于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
我不知道如何检查,如果它是一个整数或不是!我可以将其转换为字符串,然后使用索引来检查结束值,看看它们是否为零,这似乎相当麻烦。有没有更简单的方法?
当前回答
>>> 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 x%1==0:
print "is integer"
只是一个附加信息,is_integer在内部执行:
import math
isInteger = (math.floor(x) == x)
并不完全是在python中实现的,但cpython实现如上所述。
可以使用round函数来计算值。
是的,正如很多人指出的那样,在python中,当我们计算立方根的值时,它会给你一个带有一点错误的输出。要检查该值是否为整数,可以使用以下函数:
def cube_integer(n):
if round(n**(1.0/3.0))**3 == n:
return True
return False
但是记住int(n)是等价于数学的。因此,如果你找到int(41063625**(1.0/3.0)),你将得到344而不是345。
所以在使用int和立方根时要小心。
上述答案适用于许多情况,但也有遗漏。考虑以下几点:
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!")