2

In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.

Example:

5/2 gives 2
and 
-5/2 gives -3

How to get -2 when I divide -5/2 ?

Sriram
  • 999
  • 2
  • 12
  • 29
  • 5
    You may find its the better way. See Guido's explanation [here](http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html) – tdelaney Jul 26 '16 at 16:52
  • 2
    Is this just *unexpected*, or *actually problematic*? Python behaves this way because it's more useful for `-5%2` to give `1` than `-1`, and `-5/2==-3` is more consistent with `-5%2==1` than `-5/2==-2` would be. If you need your output to be consistent with other languages' interpretations of the operation, `-5/2==-3` might be a problem, but otherwise, it's usually perfectly fine. – user2357112 Jul 26 '16 at 16:54

5 Answers5

2

You should enclose division in expression like below

print -(5/2)
Indra Uprade
  • 773
  • 5
  • 12
  • 3
    This only works because your applying the negative unary operator *after* the integer division. It won't work as a general solution where `5` or `2` are variables. – Brendan Abel Jul 26 '16 at 17:02
2

As of this accepted answer:

> int(float(-5)/2)
-2

> int(float(5)/2)
2
Community
  • 1
  • 1
Michael Hoff
  • 6,119
  • 1
  • 14
  • 38
1

This happens due to python rounding integer division. Below are a few examples. In python, the float type is the stronger type and expressions involving float and int evaluate to float.

>>> 5/2
2
>>> -5/2
-3
>>> -5.0/2
-2.5
>>> 5.0/2
2.5
>>> -5//2
-3

To circumvent the rounding, you could leverage this property; and instead perform a calculation with float as to not lose precision. Then use math module to return the ceiling of that number (then convert to -> int again):

>>> import math
>>> int(math.ceil(-5/float(2)))
-2
ospahiu
  • 3,465
  • 2
  • 13
  • 24
  • Answered now, was still typing it ha, hope you change your mind about the downvote! @ritlew – ospahiu Jul 26 '16 at 16:56
  • `math.ceil` seems redundant in the last example. As mentioned in my answer, using float division with subsequent conversion into int suffices. What is the benefit of using `ceil` in this case? – Michael Hoff Jul 27 '16 at 12:07
1

You need to use float division and then use int to truncate the decimal

>>> from __future__ import division
>>> -5 / 2
-2.5
>>> int(-5 / 2)
-2

In Python 3, float division is the default, and you don't need to include the from __future__ import division. Alternatively, you could manually make one of the values a float to force float division

>>> -5 / 2.0
-2.5
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
0
>>> import math
>>> math.ceil(float(-5)/2)
-2.0
ritlew
  • 1,622
  • 11
  • 13