Re: Division/math bug in perl?
From: Alfred Z. Newmane (a.newmane.remove_at_eastcoastcz.com)
Date: 02/24/05
- Next message: Alan J. Flavell: "Re: Division/math bug in perl?"
- Previous message: A. Sinan Unur: "Re: Division/math bug in perl?"
- In reply to: darkon: "Re: Division/math bug in perl?"
- Next in thread: Anno Siegel: "Re: Division/math bug in perl?"
- Reply: Anno Siegel: "Re: Division/math bug in perl?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 24 Feb 2005 14:36:13 -0800
darkon wrote:
> Snail <snail@localhost.com> wrote:
>
>> Why is this:
>>
>> $ perl -e 'print (int (-2.6), "\n")'
>> -2
>>
>> Shouldn't it be -3? I thought converting from float to int is
>
> int() isn't really converting, it's just returning the integer part
> of the number. See the docs.
>
>> supposed to give the integer part, which is -3, and not round
>
> But the integer part of -2.6 is -2, not -3.
Not mathematically it isn't. I should be -3. Think of it like this. The
int part of 2.6 is 2, which is the /lowest/ number before the next
integer on the number line. Applying this to -2.6, the /lowest/ number
before the next integer is -3.
Maybe I can explain this better with an illustration:
Float: 1 .5 2 .5 3
2.6
| - - - - + - - - - | - - - - + * - - - |
Int: |-----------------| |------------------|
1 2
So in the other direction on the same number line:
Float: -3 .5 -2 .5 -1
-2.6
| - - - * + - - - - | - - - - + - - - - |
Int: |-----------------| |-----------------|
-3 -2
Or think of it like this: -2.6 is the same offset from -3 as +2.4 is
from 2. In other words, -2.6 and 2.4 are in the same realative postion
from the lower integral point. (Is there a better word for that?)
>> towards zero, as it seems to be doing, resulting in -2? For that
>> matter, why does c/c++ do this too?
>
> I don't know about c/c++, but this behaviour is explicitly documented
> for Perl's int():
Actually this behavior is present in C and C++. It's just the way
integer division works internally. It effectively rounds towards 0
instead of down to the lower end of the integer on the number line.
I've never quite understood why it's like it is, in C and C++, one of
side effects is the irregular (from a math perspective) behavior of the
modulus operator (%.)
I agree that it's nice that Perl's % operator does not suffer from this
mathematical short coming. ;-)
- Next message: Alan J. Flavell: "Re: Division/math bug in perl?"
- Previous message: A. Sinan Unur: "Re: Division/math bug in perl?"
- In reply to: darkon: "Re: Division/math bug in perl?"
- Next in thread: Anno Siegel: "Re: Division/math bug in perl?"
- Reply: Anno Siegel: "Re: Division/math bug in perl?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|