integer division in Ruby with negative value -


trying negative value division in ruby, e.g. -123/10, why 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 , -123%10 returns -3 in c/c++ expected.

this how designed. ruby rounds numbers towards negative infinity in case of negative division , modulo operation. not unique ruby, python , perl behaves also.

however, approach provides mathematical reason.

a / b = q remainder r

such that

b * q + r = , 0 <= r < b 

from read, how arithmetic taught in japan.

edit:

sawa pointed out how positive arithmetic taught in japan, not negative numbers. however, said, can extended negative numbers well.

sources:

ruby forums


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -