Is there a difference between using //
(Integer Division) and the built-in round()
function in Python? If I understand correctly, both will round to the nearest Integer but I'm unsure if the behaviour of both the function and the operator is exactly the same at all times. Can someone clarify? Can both of them be used "interchangeably"?
CodePudding user response:
//
is floor division, round
rounds to nearest. //
stays integer at all times, round
using /
converts to float
before rounding back, which might not work at all for large enough int
s, and can lose precision for smaller (but still large) int
s.
If you need floor division of int
s, always use //
(you can do ceiling division too, with -(-num // div)
). It's always correct, where round
(and math.floor
) might not be (for int
s exceeding about 53 bits). round
is more configurable (you can round off to a specified number of decimal places, including negative decimal places to round off to the left of the decimal point), but you want to avoid converting to float
at all whenever you can.
CodePudding user response:
>>> 5 // 2
2
>>> round(5 / 2)
2
>>> round(5 / 2, 1)
2.5
>>>
The round
function gives you more control over the precision of rounding. The //
operator provides the floor (rounds down) of dividing the two.
Consider also:
>>> round(20 / 3)
7
>>> 20 // 3
6
>>>