I got confused in the following integer math in python:
-7/3 = -3 s (-3)*3 = -9 < -7 . I understand.
-7/3 = -3
(-3)*3 = -9 < -7
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 .
7/-3 = -3
(-3)*(-3) = 9 > 7
(-3)*(-2) = 6 < 7
How it works?
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.
-inf
Here's how it works:
int(x)/int(y) == math.floor(float(x)/float(y))
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
Python is rounded. 7/3 = 2 (2 + 1/3) -7/3 = -3 (-2 + 1/3)
/ used for floating point division // used for integer division (returns an integer)
And python rounds the result down
Source: https://habr.com/ru/post/900143/More articles:Warning dialog not showing - androidHow to initialize boost :: random :: discrete_distribution using std :: vector? - c ++MapReduce using SQL Server as a data source - sql-serverUsing NSCoding in a Custom Class Subclass - objective-cSpring Mvc Controller - Removal Problem - spring-mvcHow to set the vector "discrete_distribution" C ++ - c ++How to set up a BlackBerry Phonegap project in Eclipse - MyApp.java to download index.html? - eclipseHow to store "encrypted" data in MySQL? - securityData structure / query algorithm: filter by A, sort by B, return N results - algorithmSaving html5 Canvas as data to mysql database - html5All Articles