Trying to do a negative value division in Ruby, e.g. -123/10, why it returns -13 instead of -12 ?
ruby -v
ruby 1.9.3p375 (2013-01-18) [x86_64-darwin12.2.1]
irb(main):001:0> -123/10
=> -13
irb(main):002:0> -123%10
=> 7
-123/10 returns -12 and -123%10 returns -3 in C/C++ as expected.
This is how it is designed. Ruby rounds numbers towards negative infinity in case of negative division and modulo operation. This is not unique to Ruby, Python and Perl behaves like that also.
However, this approach provides a good mathematical reason.
a / b = q
with remainder r
such that
b * q + r = a and 0 <= r < b
From what I read, this is how arithmetic is taught in Japan.
Edit:
sawa pointed out that this is how positive arithmetic is taught in Japan, not negative numbers. However, as he said, this can be extended to negative numbers as well.
Sources:
Ruby Forums
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With