Python 如何检查浮点值是否为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21583758/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a float value is a whole number
提问by chopper draw lion4
I am trying to find the largest cube root that is a whole number, that is less than 12,000.
我试图找到小于 12,000 的整数的最大立方根。
processing = True
n = 12000
while processing:
    n -= 1
    if n ** (1/3) == #checks to see if this has decimals or not
I am not sure how to check if it is a whole number or not though! I could convert it to a string then use indexing to check the end values and see whether they are zero or not, that seems rather cumbersome though. Is there a simpler way?
我不知道如何检查它是否是整数!我可以将其转换为字符串,然后使用索引来检查最终值并查看它们是否为零,但这似乎相当麻烦。有没有更简单的方法?
采纳答案by Martijn Pieters
To check if a float value is a whole number, use the float.is_integer()method:
要检查浮点值是否为整数,请使用以下float.is_integer()方法:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
The method was added to the floattype in Python 2.6.
该方法已添加到floatPython 2.6 中的类型中。
Take into account that in Python 2, 1/3is 0(floor division for integer operands!), and that floating point arithmetic can be imprecise (a floatis an approximation using binary fractions, nota precise real number). But adjusting your loop a little this gives:
考虑到在 Python 2 中,1/3是0(整数操作数的除法!),并且浮点运算可能不精确(afloat是使用二进制分数的近似值,而不是精确的实数)。但是稍微调整你的循环,这会给出:
>>> for n in range(12000, -1, -1):
...     if (n ** (1.0/3)).is_integer():
...         print n
... 
27
8
1
0
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
这意味着由于上述不精确性,任何超过 3 的立方(包括 10648)都被遗漏了:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
You'd have to check for numbers closeto the whole number instead, or not use float()to find your number. Like rounding down the cube root of 12000:
您必须检查接近整数的数字,或者不用于float()查找您的号码。就像四舍五入的立方根12000:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
If you are using Python 3.5 or newer, you can use the math.isclose()functionto see if a floating point value is within a configurable margin:
如果您使用的是 Python 3.5 或更新版本,您可以使用该math.isclose()函数查看浮点值是否在可配置的边距内:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
对于旧版本,该函数的幼稚实现(跳过错误检查并忽略无穷大和 NaN)如PEP485 中所述:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
回答by Juri Robl
You could use this:
你可以用这个:
if k == int(k):
    print(str(k) + " is a whole number!")
回答by Jakub Jirutka
回答by hughdbrown
Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.
测试立方根不是更容易吗?从 20 (20**3 = 8000) 开始,一直到 30 (30**3 = 27000)。然后你必须测试少于 10 个整数。
for i in range(20, 30):
    print("Trying {0}".format(i))
    if i ** 3 > 12000:
        print("Maximum integral cube root less than 12000: {0}".format(i - 1))
        break
回答by georg
You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:
你不需要循环或检查任何东西。只需取 12,000 的立方根并将其四舍五入:
r = int(12000**(1/3.0))
print r*r*r # 10648
回答by Daniel
How about
怎么样
if x%1==0:
    print "is integer"
回答by control_fd
The above answers work for many cases but they miss some. Consider the following:
上述答案适用于许多情况,但他们遗漏了一些。考虑以下:
fl = sum([0.1]*10)  # this is 0.9999999999999999, but we want to say it IS an int
Using this as a benchmark, some of the other suggestions don't get the behavior we might want:
将此作为基准,其他一些建议没有得到我们可能想要的行为:
fl.is_integer() # False
fl % 1 == 0     # False
Instead try:
而是尝试:
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def is_integer(fl):
    return isclose(fl, round(fl))
now we get:
现在我们得到:
is_integer(fl)   # True
isclosecomes with Python 3.5+, and for other Python's you can use this mostly equivalent definition (as mentioned in the corresponding PEP)
isclose随Python 3.5+ 一起提供,对于其他 Python,您可以使用这个几乎等效的定义(如相应的PEP 中所述)
回答by MagikCow
We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number. 
我们可以使用模 (%) 运算符。这告诉我们当我们将 x 除以 y 时我们有多少余数 - 表示为x % y。每个整数都必须除以 1,所以如果有余数,它一定不是整数。
This function will return a boolean, Trueor False, depending on whether nis a whole number.
此函数将返回一个布尔值True或False,取决于是否n为整数。
def is_whole(n):
    return n % 1 == 0
回答by Anivarth
You can use the roundfunction to compute the value. 
您可以使用该round函数来计算该值。
Yes in python as many have pointed when we compute the value of a cube root, it will give you an output with a little bit of error. To check if the value is a whole number you can use the following function:
在 python 中是的,正如许多人在我们计算立方根的值时指出的那样,它会给你一个带有一点错误的输出。要检查该值是否为整数,您可以使用以下函数:
def cube_integer(n):
    if round(n**(1.0/3.0))**3 == n:
        return True
    return False
But remember that int(n)is equivalent to math.floorand because of this if you find the int(41063625**(1.0/3.0))you will get 344 instead of 345.
但请记住,这int(n)等效于math.floor并且因此,如果您找到int(41063625**(1.0/3.0))344 而不是 345。
So please be careful when using intwithe cube roots.
所以使用int立方根时请小心。
回答by user1767754
Just a side info, is_integeris doing internally: 
只是一个侧面信息,is_integer正在内部做:
import math
isInteger = (math.floor(x) == x)
Not exactly in python, but the cpython implementation is implemented as mentioned above.
不完全是在 python 中,但是 cpython 实现是如上所述实现的。

