I’m looking for a simple explanation for how Ruby’s modulo operand works and why, in Ruby
puts 4 % 3 # 1
puts -4 % 3 # 2 <--why?
puts -4 % -3 # -1
but in PHP:
<?php
echo 4 % 3; # 1
echo -4 % 3; # -1
echo -4 % -3; # -1
Looks to me like -4 % 3 is actally 8 % 3 (8 being the difference between 4 and -4).
They can both be considered correct, depending on your definition. If
a % n == r, then it should hold that:where
q == a / n.Whether
ris positive or negative is determined by the value ofq. So in your example, either of:To put it another way, the definition of
%depends on the definition of/.See also the table here: http://en.wikipedia.org/wiki/Modulus_operator#Remainder_calculation_for_the_modulo_operation. You’ll see that this varies substantially between various programming languages.