Why not "truncation towards zero"?

  • Thread starter Artem Voroztsov
  • Start date
A

Artem Voroztsov

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...
 
M

Michael Ulm

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

I say not only is it intentional, but in this case Ruby gets it Right(TM).
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top