作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
这看起来很简单,但我找不到实现它的方法。我需要显示整数的立方根是否为整数。我在 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 == 0
、x == int(x)
和 isinstance(x,int)
但没有成功.
如有任何评论,我将不胜感激。
最佳答案
对于小数字(<~1013 左右),您可以使用以下方法:
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
关于python - 立方根是整数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621833/
我想知道如果DDMathParser支持,如何在Xcode中取数字的立方根,甚至更好。甚至更好的是,我如何扎下第x个根。 谢谢, 问候。 最佳答案 是的,DDMathParser支持以下功能: NSN
我是一名优秀的程序员,十分优秀!