如何检查浮点数是否为整数

302

我正在尝试找到最大的立方根整数,它小于12000。

processing = True
n = 12000
while processing:
    n -= 1
    if n ** (1/3) == #checks to see if this has decimals or not

不过我不确定如何检查它是否为整数!我可以将其转换为字符串,然后使用索引来检查末尾的值并查看它们是否为零,但这似乎相当麻烦。有更简单的方法吗?


4
让n的立方小于12000会使得工作更加容易。具体来说,将n取为立方根时可以达到这个目标。(即 n --> (n * n * n < 12000)) - suspectus
顺便问一下,你是指最大的整数立方体吗?对于小值,可以通过向下舍入并使用 int(12000**(1/3))**3 进行计算。 - qwr
15个回答

1
所有的答案都不错,但是一个确保有效的方法是:
def whole (n):
     return (n*10)%10==0


该函数返回True,如果它是一个整数,否则返回False。我知道我有点晚了,但这是我制作的有趣方法之一...
编辑:如下面的评论所述,一个更便宜的等价测试是:
def whole(n):
    return n%1==0

3
这与 n % 1 == 0 在功能上没有区别。在这种情况下,你执行了两个操作,对于一个更便宜的等效测试来说,这是更昂贵的。 - Zchpyvr

0

这个问题已经解决了,但我想提出一个基于数学的附加解决方案来解决函数问题。

这种方法的好处在于它计算了您的数字的整数部分,这可能根据您的一般任务而有益。

算法

  • 将您的数字的整数部分分解为其小数之和(例如,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)

注意:这里实现了解析数字的想法。


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
>>>

1
以下是如何撰写一个好的回答?的一些指南。这个提供的答案可能是正确的,但它可以从解释中受益。仅有代码的答案不被认为是“好”的答案。来自审查 - Trenton McKinney

-1

尝试使用:

int(val) == val

它将比任何其他方法提供更高的精度。


你能举个例子来支持“它会提供更高的精度”的说法吗?这似乎没有根据。 - Mark Dickinson

-1

您可以使用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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接