If you think //
and %
in Python would give you the same result as that in the static languages like C++ or Java, then you may be wrong about it. Here, I am going to explain it with C++.
In C++, if you do
cout << (167 / 12) << endl;
The ouptut is 13, where the fractional part is discarded, even though the nature result 13.9166 is pretty close to 14, it just won’t round up.
You get the same result using //
in Python.
>>> 167//12
13
because //
is equal to math.floor()
which returns the closest integer that’s smaller to the actual answer, this is the same as getting rid of the fractional part.
Though, the operation is different in two language for one of the operand is negative number. In C++ the result is -13, but Python returns a different answer.
>>> -167//12
-14
Why is that?
This is because Python rounds down the number, -14 is the closest smaller integer for -13.9166. math.ceil()
may be the correct choice for this scenario as it finds the closest larger integer.
Same goes to the mod(%
) operation
>>> 8 % 3
2
>>> -8 % 3
1
In C++, the answer is 2
and -2
accordingly.
If you need Python produce identical output as C++, You need to define functions that decide which function to use.
def div(a, b):
if (a < 0 and b < 0) or (a > 0 and b > 0):
return a // b
return math.ceil(a / b)
def mod(a, b):
sign = -1 if a < 0 or b < 0 else -1
if (a < 0 and b < 0) or (a > 0 and b > 0):
return a // b
return sign * (abs(a) % abs(b))
Conclusion
- integer division and mod in Python using
//
only equivlent to those in C++ when both numbers are of the same sign. //
is the same asmath.floor
- We can combine the
math.ceil
andmath.floor
to imitate the output in C++.