Ruby modulo 3 with negative numbers is unintuitive -


ruby modulo rules negative numbers unclear. in irb:

-7 % 3 == 2   

should 1! why?

when 1 of operands % negative, there’s no clear best answer result return. every programming language has own rules. wikipedia page modulo operation has giant table of how each programming language has decided handle this, , there’s no clear consensus:

$ # modulus sign is: $ $ curl 'http://en.wikipedia.org/w/index.php?title=modulo_operation&action=edit&section=1' \     | egrep -o 'divisor|dividend|always positive|closest zero|not defined|implementation defined' \     | sort | uniq -c | sort -nr    67 dividend   42 divisor    7 positive    4 closest 0    2 not defined    2 implementation defined 

some choose sign of left-hand operand, , right-hand operand. others don’t specify. example, the c programming language says:

the sign of result % [is] machine-dependent negative operands

instead of making particular choice how handle this, c returns whatever particular hardware or compiler being used have chosen implement! seems have been standardized in more recent versions of c programming language standards.

if want particular version in ruby, there 2 different methods call, modulo aka %, , remainder, different behaviour on negative numbers:

$ irb irb(main):001:0> -7.modulo(3) => 2 irb(main):002:0> -7.remainder(3) => -1 

in other languages don’t have built-in methods this, may end using % twice desired sign.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -