Python % Operator
% operator also supports floating-point. Floating-point values going in result in floating-point values coming out. If you haven’t played much with floating-point before, you might be a little surprised at the following little piece of math.
.1 + .1 + .1 isn’t
0.3. This has to do with how your computer stores these kinds of numbers and the floating-point standard. Mod on floating-point has the same kind of precision problem as this addition example I just showed you.
Remember how I mentioned earlier that negatives are a problem? It turns out that
% for integers and floats and
fmod() calculate negative modulus differently, and so you’ll get inconsistent results.
Here’s a large exponent, and here’s the same using the
% operator. You have a significantly different value showing up there. This problem with negatives that I’ve shown you isn’t just within Python.
03:18 Here’s an example. 13 mod 12 is 13 minus 12 times the floor of 13 over 12. Or 13 minus 12 times the floor of 1.083. The floor of 1.083 is 1, so you end up with 13 minus 12 times 1, which is a remainder of 1. Now let’s do that again with a negative number. 8 mod -3 gives you 8 minus -3 times the floor of 8 divided by -3.
% operator calculates things slightly differently. For the same operation, instead of using
floor(), it uses
trunc(). For whole numbers, this isn’t a problem.
The end result is the same calculation as you saw before. Unfortunately, for negative numbers it is a problem. When you get to the
trunc() step of 8 divided by -3, the truncation of -2.6 repeated is -2.
In Python, the
% operator uses
floor(), but the
trunc(). This is what causes the difference that I showed you earlier between negative values for
fmod(). You need to be aware of this if you’re doing modulus math on negative values.
divmod() returns two values—both the result of the division and the remainder. 12 goes into 13 once, so you get the first part of the tuple, and has a remainder of 1, giving you the second part of the tuple.
First off, strict integer division, expressed by the double slashes (
37 // 5 is
7. And secondly,
37 % 5 is
divmod(37, 5) giving you the same as these two results but in one function call. Note that
divmod() uses the same mechanism as
%. So if you’re dealing with negative values, you’ll get the kind of calculation that the
% operator does—not the kind of calculation that
fmod() uses. In Python, the
% operator is considered to have the same operator precedence as division and multiplication.
Become a Member to join the conversation.