我正在尝试找到最大的立方根整数,它小于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 whole (n):
return (n*10)%10==0
def whole(n):
return n%1==0
n % 1 == 0
在功能上没有区别。在这种情况下,你执行了两个操作,对于一个更便宜的等效测试来说,这是更昂贵的。 - Zchpyvr这个问题已经解决了,但我想提出一个基于数学的附加解决方案来解决函数问题。
这种方法的好处在于它计算了您的数字的整数部分,这可能根据您的一般任务而有益。
算法:
327=3*100+2*10+7*1
)from math import ceil, log, isclose
def is_whole(x: float) -> bool:
n_digits = ceil(log(x,10)) # number of digits of decimals at or above ones
digits = [(n//(10**i))%10 for i in range(n_digits)] # parse digits of `x` at or above ones decimal
whole = 0 # will equal the whole number part of `x`
for i in range(n_digits):
decimal = 10**i
digit = digits[i]
whole += digit*decimal
diff = whole - x
return isclose(diff, 0.0)
注意:从这里实现了解析数字的想法。
>>> 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
它将比任何其他方法提供更高的精度。
您可以使用round
函数来计算值。
是的,在Python中,当我们计算立方根的值时,它会给出一个带有一点误差的输出。要检查该值是否为整数,您可以使用以下函数:
def cube_integer(n):
if round(n**(1.0/3.0))**3 == n:
return True
return False
但请记住,int(n)
等同于 math.floor
,因此如果你使用 int(41063625**(1.0/3.0))
,你将得到 344 而不是 345。
因此,请在使用立方根时小心使用 int
。
int(12000**(1/3))**3
进行计算。 - qwr