Description
- When negative numbers are involved, the modulo operator
%
does not have the same behavior in Python and in C/C++. - Both variants are correct, but Python’s modulo is most commonly used in mathematics (number theory in particular). However C’s modulo might be more intuitive for programming…
- Python has a “true” modulo operation, while C has a remainder operation. It has a direct relation with how the negative integer division is handled, i.e. rounded towards 0 or minus infinite. Python rounds towards minus infinite and C(99) towards 0.
- In this post, we only consider the case where the numerator (分子, numérateurs) can be negative, the denominator (分母, dénominateurs) is always positive.
In Python (version 3.8.9)
Background
1 |
|
1 |
|
Python’s native //
and %
operators (rounds towards minus infinite)
1 |
|
1 |
|
Using math
to get similar behavior as in C (rounds towards 0)
1 |
|
1 |
|
Note that:
math.ceil
andmath.floor
return integers,math.fmod
returns floats.math.ceil
andmath.floor
take the sign into account, see below:
1 |
|