簡體   English   中英

在 Python 中判斷一個值是否為整數

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

我想確定 Python 中的數值是否為整數。 例如,給定:

y = x / 3

我想區分可以被 3 整除的x值,那些不是。

整數沒有小數。 如果你的意思是“檢查一個數字在 Python 中是否有小數”,你可以這樣做:

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

編輯:正如 Ollie 在這篇文章下面的評論中指出的那樣, is_integer是標准庫的一部分,因此不應像我在下面所做的那樣重新實現。

這個 function 使用了這樣一個事實,即每隔一個整數將至少有一個數可以被 2 整除而沒有余數。 nn+1中的任何非零小數表示將導致n%2(n+1)%2都有余數。 這樣做的好處是表示為浮點值的整數將返回 True。 據我所知,function 適用於正數和負數以及零。 如 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是 integer,則x % 3 == 0將為True

這是另一種方法:

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

這是有效的,因為 int(x) 基本上占據了數字的下限(例如 3.6453 -> 3)。 如果減去底數后還剩下一些東西,那它不可能是一個整數。

假設您的意思是如果包含數字的字符串也有小數點:

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

要測試它是否是完整的,您可以修改 1:

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

在 Python 2 中,將 int 除以 int 返回 int(除非使用-Qnew選項調用 python,或者from __future__ import division位於源的開頭;在這種情況下/返回一個浮點數); a //指定 integer 划分。

在 Python 3 中,如果使用“/”,則將 int 除以 int 返回浮點數,如果使用“//”,則返回 int。

如果您想知道一個 int 是否會准確地划分為另一個 int,請使用“%”查找余數。

轉換 1.0 => 1 & 轉換 1.x => 1.x

如果浮點數具有像 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)

最好在進行除法之前做出決定,假設您的 x 變量是 integer。

嘗試對浮點數進行相等性測試或比較是危險的: http://www.lahey.com/float.htm

在進行除法之前已經使用模數提供了答案,以查看一個 integer 是否可以被另一個 integer 整除是安全的。 在您進行除法並處理可能的浮點值之后,數字不再是整數或不是整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM