<

Perl 6 Numerics

Solomon Foster <colomon@gmail.com>

#perl6

Perl 6 Numerics

Numeric Roles

What is Numeric but not Real?

What math types aren't Numeric?

So, Real first

Real Methods

Gotchas

Also...

Num

Int

int

Rat

Rat II

Rat III

Rat IIII

for 0.0, 0.1 ... 1.0 -> $x {
    say $x;
}

loop ($x = 0.0; $x <= 1.0; $x += 0.1) {
    say $x;
}

Rat V

Rat VI

FatRat

Rational

Complex

Trig functions

Tricky bits I

Tricky bits II

Tricky bits III

Tricky bits IIII

Making new Real types

Money

class Money does Real {
    has $.cents;
    multi method new(Real $dollars) {
        self.bless(*, :cents(($dollars * 100).Int));
    }
    multi method new(Int :$cents) { 
        self.bless(*, :$cents); 
    }
    method Bridge() { $.cents.Bridge / 100.Bridge; }
    method perl() { "Money.new(cents => $.cents)"; }
    method isNaN() { $.cents.isNaN; }
}

Money II

Money III

multi sub infix:<+>(Money $a, Money $b) {
    Money.new(cents => $a.cents + $b.cents);
}

Money IIII

Bridge

Bridge II

Bridge III

What about new non-real numeric types?

Numbers & the bigger world of Perl 6

Examples

# Find the 201st Fibonacci number
niecza> my @fib := 1, 1, *+* ... *; say @fib[200];        
453973694165307953197296969697410619233826

Examples

# Find smallest number divisible by 2..20
sub divides-by-all-up-to($a, $b) {
    !(2..$b).grep($a !%% *);
}

my $N = [*] 2, 3, 5, 7, 11, 13, 17, 19;
my @attempts := $N, 2 * $N 
                ... 
                { divides-by-all-up-to($_, 20) };
say @attempts[*-1];

Examples

# Find smallest number divisible by 2..20
# sorear++ version
say [lcm] 2..20;
# answer is 232792560, btw

Examples

# inner core of a Mandelbrot set program
sub mandel(Complex $c) {
    my $z = 0;
    for ^$max_iterations {
        $z = $z * $z + $c;
        return True if $z.abs > 2;
    }
    return False;
}

Examples

// NURBS curve evaluation loop in C++
POINT point = HwMakePoint (0.0, 0.0, 0.0);
double den = 0.0;
for (unsigned int i = 0; i <= degree; i++)
{
    point += basis [i] * weights [span + i - degree] * points [span + i - degree];
    den += basis [i] * weights [span + i - degree];
}
point = point / den;

Examples

# NURBS curve evaluation "loop" in p6
my $slice = span - degree .. span;
my @bw = basis[0 .. degree] 
         »*« weights[$slice];
my $point = ([+] @bw »*« points[$slice]) 
            / [+] @bw;

Talk Online