in reply to Re^6: Supporting long long types in XS (NV,PV)
in thread Supporting long long types in XS

Although typically performed with a and n both being integers, many computing systems allow other types of numeric operands.

I always thought this might not be the case for Perl though.

From my 1992 copy of "Programming perl" (1st Edition; p83)
The % operator converts to integers before finding the remainder.

Though I'm not exactly sure what perlop wants to tell me aboput that topic.

Multiplicative Operators:
Binary ``%'' computes the modulus of two numbers. Given integer operands $a and $b: If $b is positive, then $a % $b is $a minus the largest multiple of $b that is not greater than $a. If $b is negative, then $a % $b is $a minus the smallest multiple of $b that is not less than $a (i.e. the result will be less than or equal to zero). Note that when use integer is in scope, ``%'' gives you direct access to the modulus operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster.
  • Comment on Re^7: Supporting long long types in XS (NV,PV)

Replies are listed 'Best First'.
Re^8: Supporting long long types in XS (NV,PV)
by BrowserUk (Patriarch) on Nov 22, 2006 at 13:01 UTC

    The POSIX pod defines fmod as:

    It returns the remainder $r = $x - $n*$y, where $n = trunc($x/$y). The $r has the same sign as $x and magnitude (absolute value) less than the magnitude of $y.

    The weird thing is, the 'obvious' implementation of mod seems to work fine?

    Perl> sub mod{ my( $a, $n ) = @_; return $a - $n * int( $a / $n ); };; Perl> print mod( 4.5, 1.25 );; ## prints 0.75 Perl> print mod( 4.5, -1.25 );; ## prints 0.75 Perl> print mod( -4.5, -1.25 );; ## prints -0.75 Perl> print mod( -4.5, 1.25 );; ## prints -0.75

    Which compares favourably with the results of my C compilers view of the world:

    Perl> use POSIX qw[ fmod ];; Perl> print fmod( 4.5, 1.25 );; ## prints 0.75 Perl> print fmod( 4.5, -1.25 );; ## prints 0.75 Perl> print fmod( -4.5, 1.25 );; ## prints -0.75 Perl> print fmod( -4.5, 1.25 );; ## prints -0.75

    I'm not sure how ruby arrives at it's take on the subject? Uses abs on the arguements, divides, truncates and multiplies, then sets the sign of the results according to the divisor?

    c:\test>\ruby\bin\ruby -e"p 4.5 % 1.25" ## prints 0.75 c:\test>\ruby\bin\ruby -e"p 4.5 % -1.25" ## prints -0.5 c:\test>\ruby\bin\ruby -e"p -4.5 % 1.25" ## prints 0.5 c:\test>\ruby\bin\ruby -e"p -4.5 % -1.25" ## prints -0.75

    That still makes more sense than the current perl implementation.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.