2010/5/3 Jay Savage <[email protected]>:
> On Sat, May 1, 2010 at 7:45 AM, Philip Potter <[email protected]> 
> wrote:
>> On 1 May 2010 12:15, Paul <[email protected]> wrote:
>>> Hello all.  How can I test to see if a number is divisible by say, 40?
>>
>> Use the modulo operator %. Given integers $x and $y, the expression $x
>
> And there's the rub: "number" ne "integer".
>
> % is fine if you're only interested in integers, but if you want to
> compare other numbers use fmod() from POSIX.pm:
>
>    perl -MPOSIX -wle 'print POSIX::fmod(35, 17.5)'

fmod is a fine replacement for % in general for testing remainders of
floating-point valued quotients, but using it as a divisibility test
requires caution and serious consideration of a different approach. It
has the same issues as a floating-point equality test: that is,
because floating-point is an inexact representation, the results can
depend on whether a value was rounded up or down:

D:\>perl -MPOSIX -wle "print POSIX::fmod(0.2, 0.1)"
0

D:\>perl -MPOSIX -wle "print POSIX::fmod(0.3, 0.1)"
0.1

D:\>perl -MPOSIX -wle "print POSIX::fmod(0.4, 0.1)"
0

D:\>perl -MPOSIX -wle "print POSIX::fmod(0.5, 0.1)"
0.1

These examples have strange results because 0.1 is not exactly
representable in binary floating-point.

Phil

--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to