From: "Mark J. Reed" Date: 2003-07-30T11:18:12+09:00 Subject: Re: -3 / 10 = -1 ?! On Mon, Jul 28, 2003 at 01:40:12PM -0700, John Andrews wrote: > 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