立方根整数?

时间:2014-05-13 02:17:55

标签: python python-3.x

这似乎很简单,但我找不到办法。我需要显示整数的立方根是否为整数。我在Python 3.4中使用了is_integer() float方法,但这并不成功。如

x = (3**3)**(1/3.0) 
is_integer(x)    
True

x = (4**3)**(1/3.0) 
is_integer(x)    
False

我尝试x%1 == 0x == int(x)isinstance(x,int)但没有成功。

我很感激任何评论。

7 个答案:

答案 0 :(得分:23)

对于小数字(< ~10 13 左右),您可以使用以下方法:

def is_perfect_cube(n):
    c = int(n**(1/3.))
    return (c**3 == n) or ((c+1)**3 == n)

这会截断浮点Cuberoot,然后测试两个最接近的整数。

对于较大的数字,一种方法是使用整数对真正的立方根进行二进制搜索,以保持精度:

def find_cube_root(n):
    lo = 0
    hi = n
    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

答案 1 :(得分:3)

在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的工作原理。)

答案 2 :(得分:1)

如果你的数字不大,我会这样做:

def is_perfect_cube(number):
    return number in [x**3 for x in range(15)]

当然,15可以用更合适的东西替换。

如果您确实需要处理大数字,我会使用sympy库来获得更准确的结果。

from sympy import S, Rational

def is_perfect_cube(number):
    # change the number into a sympy object
    num = S(number)
    return (num**Rational(1,3)).is_Integer

答案 3 :(得分:0)

我认为您应该使用round函数来获得答案。如果我必须写一个函数,那么它将如下:

def cube_integer(n):
    if round(n**(1.0/3.0))**3 == n:
        return True
    return False

你可以使用类似于int(n**(1.0/3.0)) == n**(1.0/3.0)的东西,但是在python中由于计算多维数据集根值的一些问题,它并没有精确计算。例如,int(41063625**(1.0/3.0))将为您提供344,但值应为345。

答案 4 :(得分:0)

要详细说明@nneonneo的答案,可以编写一个更通用的第k个根函数来代替cube_root,

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

答案 5 :(得分:0)

这是使用math module的另一种方法。

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行:输入您要查找的第n个根。
第4行:使用电源功能 第5行:将10位有效数字舍入为floating point approximations 第6行:打印所选数字第n个根的预览 第7行:使用modf函数获取小数和整数部分 第8行:打印立方根值的小数部分预览 第9行:如果立方根是整数,则返回 True 。如果多维数据集根值包含小数,则返回 False

答案 6 :(得分:0)

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