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

问题:如何检查浮点值是否为整数

我试图找到最大的立方根,即整数,小于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 trying to find the largest cube root that is a whole number, that is less than 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?


回答 0

要检查浮点值是否为整数,请使用以下float.is_integer()方法

>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False

该方法已添加到 float Python 2.6中类型中。

请考虑在Python 2中1/30(整数操作数的底除!),并且浮点运算可能不精确(a float是使用二进制分数的近似值,而不是精确的实数)。但是稍微调整一下循环就可以了:

>>> for n in range(12000, -1, -1):
...     if (n ** (1.0/3)).is_integer():
...         print n
... 
27
8
1
0

这意味着由于上述不精确性,错过了3个以上的立方(包括10648)的所有内容:

>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996

您将不得不检查接近整数的数字,或者不使用它float()来查找您的数字。就像四舍五入的立方根12000

>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648

如果使用的是Python 3.5或更高版本,则可以使用该math.isclose()函数查看浮点值是否在可配置的范围内:

>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True

对于较旧的版本,如PEP485中所述,该功能的简单实现(跳过错误检查并忽略无穷和NaN):

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)

To check if a float value is a whole number, use the float.is_integer() method:

>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False

The method was added to the float type in Python 2.6.

Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:

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

>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996

You’d have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 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() function to see if a floating point value is within a configurable margin:

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

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)

回答 1

我们可以使用模(%)运算符。这告诉我们当x除以y时我们有多少个余数-表示为x % y。每个整数必须除以1,因此,如果有余数,则一定不能是整数。

此函数将返回布尔值TrueFalse,具体取决于是否n为整数。

def is_whole(n):
    return n % 1 == 0

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.

This function will return a boolean, True or False, depending on whether n is a whole number.

def is_whole(n):
    return n % 1 == 0

回答 2

您可以使用此:

if k == int(k):
    print(str(k) + " is a whole number!")

You could use this:

if k == int(k):
    print(str(k) + " is a whole number!")

回答 3

您无需循环或检查任何内容。只需取12,000的立方根并四舍五入即可:

r = int(12000**(1/3.0))
print r*r*r # 10648

You don’t need to loop or to check anything. Just take a cube root of 12,000 and round it down:

r = int(12000**(1/3.0))
print r*r*r # 10648

回答 4

您可以对此进行运算。

if (n ** (1.0/3)) % 1 != 0:
    print("We have a decimal number here!")

You can use a modulo operation for that.

if (n ** (1.0/3)) % 1 != 0:
    print("We have a decimal number here!")

回答 5

测试立方体根会更容易吗?从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

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.

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

回答 6

怎么样

if x%1==0:
    print "is integer"

How about

if x%1==0:
    print "is integer"

回答 7

上面的答案在许多情况下都有效,但是却错过了一些。考虑以下:

fl = sum([0.1]*10)  # this is 0.9999999999999999, but we want to say it IS an int

使用此作为基准,其他一些建议没有达到我们可能想要的行为:

fl.is_integer() # False

fl % 1 == 0     # False

而是尝试:

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

现在我们得到:

is_integer(fl)   # True

isclosePython 3.5+一起提供,对于其他Python,您可以使用这个几乎等效的定义(如相应的PEP中所述

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

isclose comes with Python 3.5+, and for other Python’s you can use this mostly equivalent definition (as mentioned in the corresponding PEP)


回答 8

只是侧面信息,is_integer在内部进行:

import math
isInteger = (math.floor(x) == x)

并非完全在python中,但是cpython实现是如上所述实现的。

Just a side info, is_integer is doing internally:

import math
isInteger = (math.floor(x) == x)

Not exactly in python, but the cpython implementation is implemented as mentioned above.


回答 9

所有的答案都是好的,但肯定的射击方法是

def whole (n):
     return (n*10)%10==0

如果它是一个整数,则该函数返回True,否则返回False。

编辑:如下面的评论所述,一个便宜的等效测试将是:

def whole(n):
    return n%1==0

All the answers are good but a sure fire method would be

def whole (n):
     return (n*10)%10==0

The function returns True if it’s a whole number else False….I know I’m a bit late but here’s one of the interesting methods which I made…

Edit: as stated by the comment below, a cheaper equivalent test would be:

def whole(n):
    return n%1==0

回答 10

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

回答 11

尝试使用:

int(val) == val

与其他方法相比,它将提供更高的精度。

Try using:

int(val) == val

It will give lot more precision than any other methods.


回答 12

您可以使用该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立方根一起使用时请小心。

You can use the round function to compute the value.

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:

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.floor and because of this if you find the int(41063625**(1.0/3.0)) you will get 344 instead of 345.

So please be careful when using int withe cube roots.