Truncated and split Python separation

To establish the context, I’m only talking about integer arithmetic, about large integers, so going through a floating point is not an option, and using negative numbers, so the difference between gender-divided and truncated division matters.

When performing division by negative integers, typical hardware and programming languages ​​of the C family give a truncated result, for example. 1 / -2 = 0. Python 2 gives the result on the floor, for example. 1 / -2 = -1.

Regardless of the arguments, which are essentially the best, is there a way to get Python to give a truncated result? Does it really matter if you use Python 3 instead of 2?

+5
source share
4 answers

, , , int , , , float int

int(1./-2)

Python 3.X,

int(1/2)

Py 2.X

from __future__ import division
int(1/2)

, Python Integer Division Floors


float , , , , , . ,

>>> def trunc_div(a,b):
    q, r = divmod(a,b)
    if  q < 0 and r:
        q += 1
    return q

>>> trunc_div(1,-2)
0
>>> trunc_div(999999999999999999999999999999999999999999, -2)
-499999999999999999999999999999999999999999L
>>> trunc_div(999999999999999999999999999999999999999999, 2)
499999999999999999999999999999999999999999L
>>> trunc_div(1,2)
0
>>> 
+7

Python 3 ( Python 2 from __future__ import division):

>>> from __future__ import division
>>> -1 / 2
-0.5
>>> -1 // 2
-1

, , , , math.floor().

+1

, , , :

def truncdiv(a, b):
    if a < 0:
        a = -a
        b = -b
    if b < 0:
        return (a + b + 1) / b
    return a / b
+1

The gmpy2 library supports truncated partitioning:

>>> import gmpy2
>>> gmpy2.mpz(-100)//7
mpz(-15)
>>> gmpy2.t_div(gmpy2.mpz(-100),7)
mpz(-14)
>>> 

Disclaimer: I support gmpy2.

0
source

All Articles