Changing python math module behavior to divide positive numbers

Non-positive number division is very different in the C ++ and python programming languages:

//c++:
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -3
(-11) % 3 = -2
11 / (-3) = -3
11 % (-3) = 2
(-11) / (-3) = 3
(-11) % (-3) = -2

So, as you can see, C ++ minimizes the coefficient. However, python behaves like this:

#python
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -4
(-11) % 3 = 1
11 / (-3) = -4
11 % (-3) = -1
(-11) / (-3) = 3
(-11) % (-3) = -2

I cannot encode my own division function, acting like C ++, because I will use it to test C ++ calculator programs, and python does not support infix operators. Can I make python behave like C ++ when dividing integers in a simple way? For example, setting some kind of flag or something like that?

+5
source share
3 answers

., math.fmod modulo, , :

def cmod(x, y):
    return abs(x) % abs(y) * (1 if x > 0 else -1)

C-:

def cdiv(x, y):
    return abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0)

, / %. , . __div__ __mod__.

+3

, , python , ++.

, , , :

def cpp_int_div(dividend, divisor):
    a, b = dividend, divisor
    sign = 1 if (a>0 and b>0) or (a<0 and b<0) else -1
    return (abs(a)/abs(b)) * sign

def cpp_int_mod(dividend, divisor): # or just use math.fmod  (from Thomas K)
    a, b = dividend, divisor
    sign = 1 if a>0 else -1
    return (abs(a)%abs(b)) * sign

, :

print "11 / 3 = %d" % cpp_int_div(11,3)
print "11 %% 3 = %d" % cpp_int_mod(11,3)
print "(-11) / 3 = %d" % cpp_int_div(-11, 3)
print "(-11) %% 3 = %d" % cpp_int_mod(-11, 3)
print "11 / (-3) = %d" % cpp_int_div(11, -3)
print "11 %% (-3) = %d" % cpp_int_mod(11, -3)
print "(-11) / (-3) = %d" % cpp_int_div(-11, -3)
print "(-11) %% (-3) = %d" % cpp_int_mod(-11, -3)

:

11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -3
(-11) % 3 = -2
11 / (-3) = -3
11 % (-3) = 2
(-11) / (-3) = 3
(-11) % (-3) = -2
+2

decimal .

The decimal "is based on a floating-point model that has been designed to meet the needs of people and must have primary leadership - computers must provide arithmetic that works just like the arithmetic that people learn at school." - extract from decimal arithmetic specification.

However the result

import decimal
decimal.divmod(-11, 3)
>>> (-4, 1)
0
source

All Articles