What programming languages other than Python has the floor division as a single operator from the programmers' point of view? Why does it even exist? Please don't give me the answer of because it can!
I did google for it first but most results are just about accomplishing the same thing with combination of an operator and a function call. Duh!
Here is a partial answer, addressing the 2nd part of the question – Why does [an explicit floor division operator //
] even exist [in Python]? It is basically a summary of the relevant parts of PEP 238 in my words.
Up to and including Python 2.X, division with the division operator /
had different results depending on whether values of integer types or floating point types were divided (e.g. 3.0/2.0 == 1.5
; but 3/2 == 1
similar to integer division e.g. in C/C++, at least for positive numbers). This was a bit of a surprising behavior, given that Python usually doesn't care much about number types (e.g sqrt(2.0) == sqrt(2)
). Moreover, in situations where the user of a piece of Python code had control over the input data types to a division, it was really tedious for the programmer of that piece of code to ensure that the intended division was used, which made it easy to produce a potential bug (e.g. if the programmer of a function implicitly expected float inputs and thus a "true" division, but the user of the function provided integers, the result could be plain wrong).
Thus, PEP 238 proposed a path for resolving this less than ideal situation, which was accepted into the Python language specification:
//
was made available to always have the division behavior as if providing ints as input to the division. The division operator /
, for the time being, kept is original (i.e. ambiguous/unintuitive) behavior. However, by using from __future__ import division
on top of their module, programmers could already introduce a different behavior; namely, getting a "true" division with /
within their module always, no matter whether ints or floats were given as input./
now always provides "true" division. To keep Python 2's int division behavior, //
can still be used.As said, this is just the summary of the PEP in my words. For more information, I would suggest reading the original document that I linked above. It is really well-written and way more detailed. For example, it also discusses potential (rejected) alternatives on resolving the previous behavior of the /
operator.