develooper Front page | perl.perl6.language | Postings from May 2005

mod/div (was: reduce metaoperator on an empty list)

Thread Previous | Thread Next
From:
=?ISO-8859-1?Q?=22TSa_=28Thomas_Sandla=DF=29=22?=
Date:
May 23, 2005 15:49
Subject:
mod/div (was: reduce metaoperator on an empty list)
Message ID:
42925DEA.4030304@orthogon.com
mark.a.biggar@comcast.net wrote:
> There are actuall two usefull definition for %.  The first which Ada calls 'mod' always returns a value 0<=X<N and yes it has no working value that is an identity.  The other which Ada calls 'rem' defined as follows:
> 
> Signed integer division and remainder are defined by the relation: 
> 
> A = (A/B)*B + (A rem B)
> 
>    where (A rem B) has the sign of A and an absolute value less than the absolute value of B. Signed integer division satisfies the identity: 
> 
> (-A)/B = -(A/B) = A/(-B)
> 
> It does have a right side identity of +INF.

This is the truncating div-dominant definition of modulo.
The eulerian definition is mod-dominant and nicely handles
non-integer values. E.g.

  3.2 == 1.5 * 2 + 0.2 -+-->  3.2 / 1.5 == 2 + 0.2 / 1.5 == 2 + 1/15
                        |               == 2 + 0.1333...
                        +-->  3.2 % 1.5 == 0.2

Note that -3.2 == -4 + 0.8 == -4.5 + 1.3 == ...

           -3.2 / 1.5 == -3 + 1.3 / 1.5 == -3 + 0.8666... == -2.1333
           -3.2 % 1.5 ==  1.3

With integers:

      8  /   3  ==  (2 + 2/3) ==  2
      8  / (-3) == -(2 + 2/3) == -2
    (-8) /   3  == -(3 - 1/3) == -3  # this might surprise some people ;)
    (-8) / (-3) ==  (3 - 1/3) ==  3

      8  % (-3) ==   8  % 3 == 2
    (-8) % (-3) == (-8) % 3 == 1  # this as well, but it's just -3 * 3 + 1

Real valued division can be considered as % 0, that is infinite precision.
While integer arithmetic is % 1. I.e. int $x == $x - $x % 1.

    floor $x == $x - $x % 1    # -1.2 - (-1.2) % 1 == -1.2 - 0.8 == -2
    ceil  $x == 1 + floor $x
    round $x == floor( $x + 0.5 )
    trunc $x == $x < 0 ?? ceil $x :: floor $x

To @Larry: how are mod and div defined in Perl6?
-- 
TSa (Thomas SandlaƟ)


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About