Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, what is a good way to round towards zero in integer division?

Tags:

1/2 

gives

0 

as it should. However,

-1/2 

gives

-1 

, but I want it to round towards 0 (i.e. I want -1/2 to be 0), regardless of whether it's positive or negative. What is the best way to do that?

like image 442
blacktrance Avatar asked Nov 12 '13 01:11

blacktrance


People also ask

How do you round integer division in Python?

In Python, we can perform floor division (also sometimes known as integer division) using the // operator. This operator will divide the first argument by the second and round the result down to the nearest whole number, making it equivalent to the math. floor() function.

How do you round up in integer division?

If the divisor and dividend have the same sign then the result is zero or positive. If the divisor and dividend have opposite signs then the result is zero or negative. If the division is inexact then the quotient is rounded towards zero. That is, up if it is negative, and down if it is positive.

How do you round to zero?

Round-toward-zero: As its name suggests, this refers to rounding in such a way that the result heads toward zero. For example, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, and 3.9 will all be rounded to 3. Similarly, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -3.7, -3.8, and -3.9 will all be rounded to -3.

Does Python round up or down integer division?

Some programming languages give up (3), and make div round down (Python, Ruby). In some (rare) cases the language offers multiple division operators.


1 Answers

Do floating point division then convert to an int. No extra modules needed.

Python 3:

>>> int(-1 / 2) 0 >>> int(-3 / 2) -1 >>> int(1 / 2) 0 >>> int(3 / 2) 1 

Python 2:

>>> int(float(-1) / 2) 0 >>> int(float(-3) / 2) -1 >>> int(float(1) / 2) 0 >>> int(float(3) / 2) 1 
like image 109
Tim Avatar answered Oct 14 '22 22:10

Tim