2016-04-15 51 views
1

在python3中,整數除法與python 2.7.3不同。有沒有辦法確保除法後沒有餘數的數字作爲整型返回,而除數之後有餘數的數作爲浮點返回?Python3分區:當沒有餘數時返回int,當有餘數時返回float。

我希望能夠檢查:

if (instanceof(x/n, int)): 
    # do something 

下在python3發生:

>>> 4/2 
2.0 
>>> 5/2 
2.5 

有一些方法,使分裂的行爲也是這樣嗎?

>>> 4/2 
2 
>>> 5/2 
2.5 

回答

1

我不認爲有辦法讓它自動的,但你總是可以做一個快速檢查後,將其轉化:

r = 4/2 
if r%1==0: 
    r=int(r) 
+1

我很想知道一個解決方案,假設浮點除法將可靠地產生精確的結果,即使數學邏輯應該。浮點錯誤是這樣的邏輯混亂的東西。 'int'數學在Python中是無損的,'float'數學是有損的,所以如果你需要可靠的結果,你需要首先使用'int'數學,而'float'作爲後備。 – ShadowRanger

+1

'r =(10 ** 20 + 1)/ 2'就是失敗的一個例子。 – user2357112

+0

的確如此。我考慮過那些不太可能失敗的情況,比如問題中的問題。 – cgarciahdez

5

你必須實現它自己。顯而易見的方法是:

def divspecial(n, d): 
    q, r = divmod(n, d) # Get quotient and remainder of division (both int) 
    if not r: 
     return q   # If no remainder, return quotient 
    return n/d   # Otherwise, compute float result as accurately as possible 

當然,如果你只是想檢查部門將準確與否,不要用廢話的功能等上面來檢查:

if isinstance(divspecial(x, n), int): 

直接測試其餘部分:

if x % n == 0: # If remainder is 0, division was exact