我试着找出最大的立方根它是一个整数,小于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
我不知道如何检查,如果它是一个整数或不是!我可以将其转换为字符串,然后使用索引来检查结束值,看看它们是否为零,这似乎相当麻烦。有没有更简单的方法?
当前回答
要检查浮点值是否为整数,使用float.is_integer()方法:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
该方法在Python 2.6中被添加到float类型。
考虑到在Python 2中,1/3等于0(整数操作数的底除法!),浮点算术可能是不精确的(浮点是使用二进制分数的近似值,而不是精确的实数)。但是稍微调整一下你的循环就会得到:
>>> 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()函数来查看浮点值是否在可配置的范围内:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
对于旧版本,PEP485中提到的该函数的简单实现(跳过错误检查并忽略无穷大和NaN):
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)
其他回答
>>> 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
>>>
尝试使用:
int(val) == val
它比其他任何方法都更精确。
你可以用这个:
if k == int(k):
print(str(k) + " is a whole number!")
如何
if x%1==0:
print "is integer"
可以使用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和立方根时要小心。