Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between 3/2 and -3/2?

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?

like image 878
jibin jose Avatar asked Nov 04 '14 17:11

jibin jose


3 Answers

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.

like image 198
Henry Keiter Avatar answered Nov 17 '22 18:11

Henry Keiter


-3/2 == -1.5 , floor(-1.5)  = -2

likewise

 3/2 == 1.5 , floor(1.5)  = 1
like image 4
Joran Beasley Avatar answered Nov 17 '22 18:11

Joran Beasley


Python has two division operators.

  1. /

  2. //

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 expression 11 // 4 evaluates to 2 in contrast to the 2.75 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.

like image 1
thefourtheye Avatar answered Nov 17 '22 17:11

thefourtheye