From what I understand, the integer division //
operator is guaranteed to return an integer. However, while 2 // 1 == 1
, I also get 2.0 // 1 == 2.0
. Why doesn't python produce an integer, and, is it always safe to cast the output to int
?
Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the 'floor' function applied to the result.
Behavior of the division operator in Python 2.7 and Python 3 // is not "used for integer output". // is the result of the floor() function to the result of the division, which in turns yields an integer if the two operands are integers and a float if at least one of them is a float, for types coherence.
The result of regular division is always a float, whereas if one of the operands is a float in floor division, then the output will be a float. print(2 / 2, "\tis a float.") print(15 // 4, "\tis an int.")
If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point. This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected.
You misunderstood the operator. It is a floor division operator, not an integer division operator.
For floating point inputs, it'll still return a floored float value.
From the Binary arithmetic operations section:
The
/
(division) and//
(floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result.
The result of flooring is safe to convert to an integer.
Note that Python applies these rules to almost all numeric types when used in binary arithmetic operations, division and floor division are not exceptional here, nor is this specific to integers and floats (try it with import fractions
then 2 // fractions.Fraction(1, 1)
for example). The only exception here are complex numbers, for which floor division, modulo operator or divmod()
are not defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With