13.div(-4) == -4 and 13.modulo(-4) == -3 so that
(-4 * -4) + -3 == 13
and you get a consistent attitude
(b * (a/b)) + a.modulo(b) == a
Why is 13.div (-4) rounded to -4 and not to -3?
It's a delusion. 13.div(-4) is not rounded at all. This is an integer division and follows the self-consistent rules for working with integers and modular arithmetic. The rounding logic described in your link approaches it and then is applied sequentially when working with the same divmod operation when one or both of Float s parameters. Mathematical operations with negative or fractional numbers often extend to simpler and more intuitive results on natural numbers of this kind. For example. this follows the same logic of how fractional and negative powers or non-integer factorials are created from their positive integer variants.
In this case, it's all about the self-consistency of divmod , but not about rounding in general.
Ruby designers had the opportunity to do when dealing with negative numbers, not all languages ββwill give the same result. However, once it has been decided, Ruby will return the modulo sign of the result corresponding to the divisor (as opposed to matching the division as a whole), which sets how the rest of the numbers work.
Is there any rule or convention in Ruby for rounding negative numbers?
Yes. Rounding a floating-point number means returning the nearest numeric integer. When there are two equally close integer numbers, Ruby rounds are equal to an integer other than 0. This is a completely separate design decision from how the methods of integer division and modulo arithmetic work.
If so, why is the following code not rounded? -3.25.round() #3
I assume you mean the result for reading -3 . The round method is not "rounded". It "rounds closer." -3 is the closest integer to -3.25 . Ruby designers really had to make a choice, but what to do with -3.5.round() # -4 . Some languages ββwill instead return -3, rounding this number.
Neil slater
source share