简体   繁体   English

在 Python 中判断一个值是否为整数

[英]Determining whether an value is a whole number in Python

I would like to determine if a numeric value in Python is a whole number.我想确定 Python 中的数值是否为整数。 For example, given:例如,给定:

y = x / 3

I want to distinguish between values of x which are evenly divisible by 3 those which are not.我想区分可以被 3 整除的x值,那些不是。

Integers have no decimals.整数没有小数。 If you meant "check if a number got decimals in Python", you can do:如果你的意思是“检查一个数字在 Python 中是否有小数”,你可以这样做:

not float(your_number).is_integer()
if x % 3 == 0:
    print 'x is divisible by 3'

Edit: As Ollie pointed out in the comment below this post, is_integer is part of the standard library and should therefore not be reimplemented as I did below.编辑:正如 Ollie 在这篇文章下面的评论中指出的那样, is_integer是标准库的一部分,因此不应像我在下面所做的那样重新实现。

This function uses the fact that every other whole number will have at least one number divisible by two with no remainder.这个 function 使用了这样一个事实,即每隔一个整数将至少有一个数可以被 2 整除而没有余数。 Any non-zero fractional representation in either n or n+1 will cause both n%2 and (n+1)%2 to have a remainder. nn+1中的任何非零小数表示将导致n%2(n+1)%2都有余数。 This has the benefit that whole numbers represented as float values will return True.这样做的好处是表示为浮点值的整数将返回 True。 The function works correctly for positive and negative numbers and zero as far as I can determine.据我所知,function 适用于正数和负数以及零。 As mentioned in the function, it fails for values very close to an integer.如 function 中所述,对于非常接近 integer 的值,它会失败。

def isInteger(n):
    """Return True if argument is a whole number, False if argument has a fractional part.

    Note that for values very close to an integer, this test breaks. During
    superficial testing the closest value to zero that evaluated correctly
    was 9.88131291682e-324. When dividing this number by 10, Python 2.7.1 evaluated
    the result to zero"""

    if n%2 == 0 or (n+1)%2 == 0:
        return True
    return False

x % 3 == 0 will be True if x / 3 is an integer.如果x / 3是 integer,则x % 3 == 0将为True

Here's another method:这是另一种方法:

x = 1/3  # insert your number here
print(x - int(x) == 0)  # True if x is a whole number, False if it has decimals.

This works because int(x) essentially takes the floor of the number (ex. 3.6453 -> 3).这是有效的,因为 int(x) 基本上占据了数字的下限(例如 3.6453 -> 3)。 If there's something left over once you subtract the floor, it can't have been a whole number.如果减去底数后还剩下一些东西,那它不可能是一个整数。

assuming you mean if a string containing digits also has a decimal point:假设您的意思是如果包含数字的字符串也有小数点:

Python 2.6.6 (r266:84292, Apr 20 2011, 11:58:30) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> number='123.4'
>>> '.' in number
True
>>> number='123'
>>> '.' in number
False
>>>

To test if it's integral you could mod 1:要测试它是否是完整的,您可以修改 1:

>>> 1.0/3 % 1
0.33333333333333331
>>> 1/3 % 1
0

In Python 2, dividing an int by an int returns an int (unless python was invoked with the -Qnew option, or a from __future__ import division is at the beginning of the source; in that case / returns a float);在 Python 2 中,将 int 除以 int 返回 int(除非使用-Qnew选项调用 python,或者from __future__ import division位于源的开头;在这种情况下/返回一个浮点数); a // specifies integer division. a //指定 integer 划分。

In Python 3, dividing an int by an int returns a float if you use "/", or an int if you use "//".在 Python 3 中,如果使用“/”,则将 int 除以 int 返回浮点数,如果使用“//”,则返回 int。

If you want to know whether an int will divide into another int exactly, use "%" to look for a remainder.如果您想知道一个 int 是否会准确地划分为另一个 int,请使用“%”查找余数。

convert 1.0 => 1 & convert 1.x => 1.x转换 1.0 => 1 & 转换 1.x => 1.x

This code if float numbers has decimal part like 1.5 will return 1.5 & if it is 35.00 it return 35:如果浮点数具有像 1.5 这样的小数部分,则此代码将返回 1.5,如果是 35.00,则返回 35:

a = ReadFrom()    
if float(a).is_integer(): # it is an integer number like 23.00 so return 23
       return int(a)
 else: # for numbers with decimal part like : 1.5 return 1.5
       return float(a)

It is best to make your determination before doing the division, assuming that your x variable is an integer.最好在进行除法之前做出决定,假设您的 x 变量是 integer。

Trying to do equality tests or comparisons on floating point numbers is dangerous: http://www.lahey.com/float.htm尝试对浮点数进行相等性测试或比较是危险的: http://www.lahey.com/float.htm

The answer already provided using modulus before doing the division to see if one integer is divsible by the other integer is safe.在进行除法之前已经使用模数提供了答案,以查看一个 integer 是否可以被另一个 integer 整除是安全的。 After you do a division and are dealing with possibly floating point values, then numbers are no longer exactly integers or not.在您进行除法并处理可能的浮点值之后,数字不再是整数或不是整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM