perlroundingpdl

Rounding towards zero on a PDL


I have a PDL (type double) of mixed values (both positive and negative). I want to round each entry towards zero. So +1.2 becomes +1, +1.7 becomes +1, -1.2 becomes -1, and -1.7 becomes -1,

I thought of using int(), but it doesn't work on PDL types.

I can also use round(abs($x) - 0.5) * ($x <=> 0), but not sure how to use this logic on a PDL.

Pointers?


Solution

  • The documentation of the rint function in PDL::Math says:

    If you want to round half-integers away from zero, try floor(abs($x)+0.5)*($x<=>0).

    Just change it slightly to make it work the way you want:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    use PDL;
    
    my $pdl = 'PDL'->new(
        [  1,  1.3,  1.9,  2,  2.1,  2.7 ],
        [ -1, -1.3, -1.9, -2, -2.1, -2.7 ]
    );
    $pdl = floor(abs($pdl)) * ($pdl <=> 0);
    print $pdl;
    

    Output:

    [
     [ 1  1  1  2  2  2]
     [-1 -1 -1 -2 -2 -2]
    ]