Playing around with some numbers may help:
from math import remainder, fmod
# in case x is a multiple of y
remainder(20, 4) # 0.0
fmod(20, 4) # 0.0
# in any other case
remainder(20, 3) # -1.0
fmod(20, 3) # 2.0
So what we see here is that the remainder, as stated in the docs, returns the difference between x and the closest integer multiple of y. As 20 lies between 18 and 21 (the 6- and 7-multiples of 3), it chooses whichever is closer to x. In this case it is 21, so the difference between x and 21 is -1.0.
In contrast, fmod returns the result of 20 mod 3, which is 2.0. I explicitly do not use the % operator, as the docs state that the result may differ.
Videos
As Thomas K said, use math.fmod for modulo, or if you really want you can define it yourself:
def cmod(x, y):
return abs(x) % abs(y) * (1 if x > 0 else -1)
And this function should emulate C-style division:
def cdiv(x, y):
return abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0)
You said that you must use the / and % operators. This is not possible, since you can't override the operator for built-ins. You can however define your own integer type and operator overload the __div__ and __mod__ operators.
There is no flag you can set to make python division to act like c++.
You advised that you can't code your own division function, but if you change your mind you can do this:
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
This shows that it acts according to your specification:
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)
Which gives:
11 / 3 = 3
11 % 3 = 2
(-11) / 3 = -3
(-11) % 3 = -2
11 / (-3) = -3
11 % (-3) = 2
(-11) / (-3) = 3
(-11) % (-3) = -2