Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer division in Ruby with negative value

Tags:

ruby

division

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.

like image 432
ccy Avatar asked May 13 '13 20:05

ccy


1 Answers

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

like image 114
emre nevayeshirazi Avatar answered Sep 28 '22 09:09

emre nevayeshirazi