Python integer division

I got confused in the following integer math in python:

-7/3 = -3 s (-3)*3 = -9 < -7 . I understand.

7/-3 = -3 I do not understand how this is defined. (-3)*(-3) = 9 > 7 . In my opinion, this should be -2, because (-3)*(-2) = 6 < 7 .

How it works?

+6
source share
5 answers

From the documentation :

For (simple or long) integer division, the result is an integer. The result is always rounded to minus infinity : 1/2 is 0, (-1) / 2 is -1, 1 / (- 2) is -1, and (-1) / (- 2) is 0.

Rounding towards -inf explains the behavior you see.

+13
source

Here's how it works:

 int(x)/int(y) == math.floor(float(x)/float(y)) 
+4
source

Extension of answers from aix and robert.

The best way to think about this is to round down (to minus infinity) a floating-point result:

-7/3 = floor(-2.33) = -3

7/-3 = floor(-2.33) = -3

+1
source

Python is rounded. 7/3 = 2 (2 + 1/3) -7/3 = -3 (-2 + 1/3)

0
source

/ used for floating point division // used for integer division (returns an integer)

And python rounds the result down

0
source

Source: https://habr.com/ru/post/900143/


All Articles