-1

i have a question about division of negative number in python3

when I do the calculation for 6//(-132) why it is -1 intead of 0 .

what is the mechanism that python deal with this division?

Aaron Wei
  • 85
  • 1
  • 5

3 Answers3

6

In fact, you're not using Python 3.x, you're using Python 2.x and what you see is the result of integer division, which was the default back then:

>>> 1/(-2) 
-1
>>> -1/2
-1
>>> -23/45
-1

To get the expected results in Python 2.x, try this:

from __future__ import division

>>> 1/(-2) 
-0.5
>>> -1/2
-0.5
>>> -23/45
-0.5111111111111111

Now, for the question after the edit: When you do integer division // the value will be rounded down toward the negative value of -1. (this is also known as "floor division"). See this post for further details.

>>> 6 / (-132)
-0.045454545454545456
>>> 6 // (-132)
-1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Well most probably you are not using python 3 because in my idle python 3.8 on 1/-2 it shows -0.5 and the same in case of -1/2

Divyessh
  • 2,540
  • 1
  • 7
  • 24
1

In the remainder operation the python always takes the floor or the greatest integer function as the answer

Divyessh
  • 2,540
  • 1
  • 7
  • 24