立方根是整数吗?
这看起来很简单,但我找不到方法来实现。我需要判断一个整数的立方根是否也是整数。我在Python 3.4中用了is_integer()
这个浮点数的方法,但没有成功。因为
x = (3**3)**(1/3.0)
is_integer(x)
True
但是
x = (4**3)**(1/3.0)
is_integer(x)
False
我试过x%1 == 0
、x == int(x)
和isinstance(x,int)
,结果也都不行。
如果有人能给点建议,我会很感激。
8 个回答
1
在 Python 3.11
中,你可以使用 math.cbrt
来计算立方根。
x = 64
math.cbrt(x).is_integer
(或者)
你也可以使用 numpy.cbrt
来实现同样的功能。
import numpy as np
x = 64
np.cbrt(x).is_integer
1
这是另一种使用 数学模块 的方法。
import math
num = int(input('Enter a number: '))
root = int(input('Enter a root: '))
nth_root = math.pow(num, (1/root))
nth_root = round(nth_root, 10)
print('\nThe {} root of {} is {}.'.format(root, num, nth_root))
decimal, whole = math.modf(nth_root)
print('The decimal portion of this cube root is {}.'.format(decimal))
decimal == 0
第1行:导入数学模块。
第2行:输入你想要计算根号的数字。
第3行:输入你想要的根的次数,比如平方根、立方根等。
第4行:使用幂函数来进行计算。
第5行:结果保留到10位有效数字,以应对 浮点数近似 的问题。
第6行:打印出你选择的数字的根的预览。
第7行:使用modf函数来获取小数部分和整数部分。
第8行:打印出立方根值的小数部分的预览。
第9行:如果立方根是整数,返回 True;如果立方根有小数部分,返回 False。
1
为了更详细地解释@nneonneo的回答,我们可以写一个更通用的k次根函数,来替代立方根函数。
def kth_root(n,k):
lb,ub = 0,n #lower bound, upper bound
while lb < ub:
guess = (lb+ub)//2
if pow(guess,k) < n: lb = guess+1
else: ub = guess
return lb
def is_perfect_cube(n):
return kth_root(n,3) == n
6
在SymPy这个库里,有一个叫做 integer_nthroot
的函数,它可以快速找到一个数字的整数n次根,并且还会告诉你这个结果是否是准确的。
>>> integer_nthroot(primorial(12)+1,3)
(19505, False)
所以你的函数可以是
def is_perfect_cube(x): return integer_nthroot(x, 3)[1]
(而且因为SymPy是开源的,你可以查看这个函数的具体实现,了解 integer_nthroot
是怎么工作的。)
30
对于小数字(大约小于10的13次方),你可以使用以下方法:
def is_perfect_cube(n):
c = int(n**(1/3.))
return (c**3 == n) or ((c+1)**3 == n)
这个方法会先把浮点数的立方根截断,然后测试两个最接近的整数。
对于更大的数字,有一种方法是使用整数进行二分查找来找到真实的立方根,这样可以保持精确度:
def find_cube_root(n):
lo = 0
hi = 1 << ((n.bit_length() + 2) // 3)
while lo < hi:
mid = (lo+hi)//2
if mid**3 < n:
lo = mid+1
else:
hi = mid
return lo
def is_perfect_cube(n):
return find_cube_root(n)**3 == n