I am beginner in programming and Python. I am doing some simple maths operations. So 3/2
in Python interpreter gives 1
as we know. But -3/2
gives -2
. Can you point out the difference here?
In Python 2, /
performs integer division. What this means is that the result, if it is not an integer, is rounded down to the next integer value. When the value is negative, this naturally rounds to a greater-magnitude negative number.
Intuitively, the result of integer division is simply the mathematical floor of the result of float division. For this reason, integer division is also commonly referred to as floor division.
floor(1.5) # Returns 1.0
floor(-1.5) # Returns -2.0
It's possible to alter this behavior in Python 2 by putting from __future__ import division
at the top of your module. This import will make the /
operator indicate only true division (float division), and enable explicit floor division (integer division) with the //
operator. These conventions are the standard in Python 3.
from __future__ import division
print(3/2) # 1.5
print(3//2) # 1
As @Dunes notes in the comments, it's worth noting that -
has a higher precedence than /
, and therefore -3/2
is equivalent to (-3)/2
rather than -(3/2)
. If the division were applied first, the result would indeed be -1
.
-3/2 == -1.5 , floor(-1.5) = -2
likewise
3/2 == 1.5 , floor(1.5) = 1
Python has two division operators.
/
//
Here, //
will always round the result to the nearest integer (irrespective of the type of operands). This is called floor division. But /
will round to the nearest integer, if both the operands are integers wheres it does the actual division if either of the operands is a float.
The difference can be clearly understood with this example,
>>> 11/4
2
>>> 11.0/4
2.75
>>> 11//4
2
>>> 11.0//4.0
2.0
Quoting from Python Documentation on floor division,
Mathematical division that rounds down to nearest integer. The floor division operator is
//
. For example, the expression11 // 4
evaluates to2
in contrast to the2.7
5 returned by float true division. Note that(-11) // 4
is-3
because that is-2.75
rounded downward. See PEP 238.
The last line in the quoted text would be the answer to your actual question.
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