Saturday, March 14, 2009

Untitled

In my online RUBY class, I missed one of the quiz questions from lesson one! The difficulty came from an apparently inconsistent behavior of the modulus operator (%).

Note the weird behavior demonstrated above.

Here is my explanation. The behavior is actually weird, but can be explained--if you know that ruby always keeps the sign of the divisor (the second value) and understand what modulus is asking for. Modulus returns the remainder after summing successive units until no more can be included without going higher than the goal.

-5 % 3

will therefore give a + (non-negative) result. The value of the result is calculated as follows:
1 unit of -3 is higher than the goal of -5
2 units of -3 (=-6) is not higher than the goal. The remainder, the difference between -6 and -5, is 1.
The result is 1 (sign matches the second number).
Its doubtful anyone uses % with numbers of different signs anyway.

Summary

  • If the numbers differ in their signs, you overshoot the goal and find the difference.
  • The sign of the result always matches the sign of the divisor.


No comments: