Why? -9 / 5 = -2 with a remainder of 1, because -2 * 5 + 1 = -9.
The math checks out, it's your intuition that's wrong. If you want the numbers to behave as if they were positive, use their absolute value and then adjust the sign.
···
On Sun, 23 Dec 2012 19:24:00 +0100, Derrick B. <lists@ruby-forum.com> wrote:
But I want a "correct" answer, which is not -2. Hence:
On Sun, 23 Dec 2012 19:24:00 +0100, Derrick B. <lists@ruby-forum.com> wrote:
--
* Se la Strada e la sua Virtu' non fossero state messe da parte,
* K * Carlo E. Prelz - fluido@fluido.as che bisogno ci sarebbe
* di parlare tanto di amore e di rettitudine? (Chuang-Tzu)
But I want a "correct" answer, which is not -2. Hence:
Why? -9 / 5 = -2 with a remainder of 1, because -2 * 5 + 1 = -9.
The math checks out, it's your intuition that's wrong. If you want the
numbers to behave as if they were positive, use their absolute value and
then adjust the sign.
How can my intuition be wrong when you are not asking in what way I
require that arithmetic operation to perform? You are showing your
intuition to be wrong.
"The math checks out"
How? What is your basis for that statement? In the general sense of
"math", an answer of "-1.8" would be that which checks out. Ruby rounds
to negative infinity when one of two operands of an integer division
operation is negative, hence -9 / 5 = -2 ("The Ruby Programming
Language" book). So, the correct statement is "The Ruby math checks
out"
ruby -le 'print (-9 / 5).to_i'
output: -2
and I can add to it with "The Perl math checks out"
perl -le 'print int(-9 / 5)'
output: -1
···
On Sun, 23 Dec 2012 19:24:00 +0100, Derrick B. <lists@ruby-forum.com> > wrote:
Both are right. You can perform the division is two ways: one that gives negative remainders and one that doesn't. The precise behavior of Ruby implementation is documented here: Class: Numeric (Ruby 1.9.3)
I suggest just not doing integer division with negative numbers, less trouble.
···
On Sun, 23 Dec 2012 21:39:42 +0100, Carlo E. Prelz <fluido@fluido.as> wrote:
I don't know which one is right, but I thought both C and Ruby were
doing integer maths in the same way...
I don't know which one is right, but I thought both C and Ruby were
doing integer maths in the same way...
Carlo
So did I until I translated a C++ homework assignment to Perl, then to
Ruby.
(See my other thread if you do not already have enough to read. heh )
C++ and Perl are similar in how they round negative quotients of integer
division , but from what I read in "The Ruby Programming Language" book,
page 45, Ruby is opposite.