2016-04-15 126 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 
相关问题