Is it intentional that (-1/2) gives -1 ?

Please, give me links if there is any rationale.

(i have ruby 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32] )

#
Ruby

puts -1/2; # => -1

// C (

#include <stdio.h>

int main() {

printf(“%d\n”, -1/2); // => 0 (in most platforms. )

return 0;

}

It looks like standard C9x states not only equation b*(a/b) + a%b ==

a

but also “truncation towards zero”.

In http://www.open-std.org/JTC1/SC22/WG14/www/docs/C99RationaleV5.10.pdf

one could read (6.5.5, page 74):

… In Fortran, however, the result will always

truncate toward zero, and the overhead seems to be acceptable to the

numeric

programming community. Therefore, C99 now requires similar behavior,

which

should facilitate porting of code from Fortran to C…

Artem V. wrote:

Is it intentional that (-1/2) gives -1 ?

I say not only is it intentional, but in this case Ruby gets it

Right™.

Please, give me links if there is any rationale.

No links, but rounding to minus infinity is mathematically and

conceptionally

the simplest way to do it. The benefit is, that there are fewer special

cases to deal with when numbers get negative.

-C code snipped-

It looks like standard C9x states not only equation b*(a/b) + a%b == a

but also “truncation towards zero”.

This equation is fulfilled in Ruby as well. It also shows one reason why

the C implementation is worse. To make this equation correct for

negative a,

the expression a%b has to be negative as well. So, the range of values

for

a%b differs for positive and negative values of a, whereas in Ruby it

is

always in the range (0…b). This is tremendously useful.

In http://www.open-std.org/JTC1/SC22/WG14/www/docs/C99RationaleV5.10.pdf

one could read (6.5.5, page 74):

… In Fortran, however, the result will always

truncate toward zero, and the overhead seems to be acceptable to the

numeric

programming community. Therefore, C99 now requires similar behavior, which

should facilitate porting of code from Fortran to C…

So, this is saying, C does this because of backwards compatibility with

Fortran, which didn’t get it right. There is no reason for Ruby to be

backwards compatible with Fortran.

HTH,

Michael