-3 / 10 = -1 ?!

J

John Andrews

Why does this program:

print -3 / 10, "\n"

print -1?

If I underflow a negative int in C, I get zero.

If I underflow a negative integer in Perl (using "use integer"),
I get zero.

Why does Ruby give me -1?

This behavior is not described (in any place I can find) in
the pickaxe book.

Thanks,

JA
 
M

Mark J. Reed

Why does this program:

print -3 / 10, "\n"

print -1?

Because -1 == floor(-3/10). Truncation toward zero, which is the usual
behavior in programming languages (though BASIC is a venerable exception)
is not mathematically well-defined. Consistently either rounding down to the
greatest integer smaller than the real number (floor), or up to the smallest
integer greater than it (ceiling), is much better behaved mathematically.
For instance, it's easy to write a function to convert a Gregorian calendar
date to the corresponding Julian Day number. If you use floor and ceiling
rather than truncation, this easy function will automatically work for
zero and negative values of either the year or the Julian Day (where the
year number is always interpreted as AD, and 0 AD = 1 BC, -1 AD = 2 BC,
etc.). If you use truncation, then you have to special case it for
zero and negative numbers in both directions.

On a somewhat related note, the mathematical definition of the "modulus"
operator (%) is this:

x % y == x - y * floor(x/y)

Which means 1. that it works for any real numbers, not just integers
or positive ones, and 2. the result is positive for any positive y.
That is, -1 % 5 is 4, not -1. Most C implementations and many
languages which inherited the % syntax disagree with this result,
substituting truncation for floor, as did earlier versions of Perl.
But in Ruby and modern Perl, % generates the mathematically more
useful answer.

-Mark
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top