Python 3 int division operator is returning a float?

前端 未结 2 1924
天命终不由人
天命终不由人 2020-12-20 23:01

In one of my assignments I came across a weird implementation, and I was curious if it\'s a bug or the designed behavior.

In Python 3, division by / ret

相关标签:
2条回答
  • 2020-12-20 23:33

    I hope this clarifies the situation:

    / Division

    Divides left hand operand by right hand operand

    b / a = 2
    

    // Floor Division

    The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity)

    9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
    

    https://www.tutorialspoint.com/python/python_basic_operators.htm

    0 讨论(0)
  • 2020-12-20 23:43

    From PEP-238, which introduced the new division (emphasis mine):

    Semantics of Floor Division

    Floor division will be implemented in all the Python numeric types, and will have the semantics of:

    a // b == floor(a/b)
    

    except that the result type will be the common type into which a and b are coerced before the operation.

    Specifically, if a and b are of the same type, a//b will be of that type too. If the inputs are of different types, they are first coerced to a common type using the same rules used for all other arithmetic operators.

    In particular, if a and b are both ints or longs, the result has the same type and value as for classic division on these types (including the case of mixed input types; int//long and long//int will both return a long).

    For floating point inputs, the result is a float. For example:

    3.5//2.0 == 1.0
    

    For complex numbers, // raises an exception, since floor() of a complex number is not allowed.

    For user-defined classes and extension types, all semantics are up to the implementation of the class or type.

    So yes, it is supposed to behave that way. "// means integer division and should return an integer" - not quite, it means floor division and should return something equal to an integer (you'd always expect (a // b).is_integer() to be true where either operand is a float).

    0 讨论(0)
提交回复
热议问题