Python3除法:当没有余数时返回int,当有余数时返回浮点数?

tki*_*der 1 python floating-point python-3.x

在python3中,整数除法的工作方式与python 2.7.3不同.有没有办法确保在除法后没有余数的数字作为int返回,而在除法后有余数的数字作为浮点数返回?

我希望能够检查:

if (instanceof(x/n, int)):
    # do something
Run Code Online (Sandbox Code Playgroud)

python3中发生以下情况:

>>> 4 / 2
2.0
>>> 5 / 2
2.5
Run Code Online (Sandbox Code Playgroud)

有没有办法让分裂这样做?

>>> 4 / 2
2
>>> 5 / 2
2.5
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 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
Run Code Online (Sandbox Code Playgroud)

当然,如果您只是想检查分区是否准确,请不要像上面的函数那样使用废话来检查:

if isinstance(divspecial(x, n), int):
Run Code Online (Sandbox Code Playgroud)

只需直接测试其余部分:

if x % n == 0:  # If remainder is 0, division was exact
Run Code Online (Sandbox Code Playgroud)