Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing list of lists in Raku

I am trying to sum a list of lists in Raku. Example taken from here:


my $arr = ([1e50, 1, -1e50] xx 1000);

say (flat |$arr).sum; # output 0

# https://docs.raku.org/language/operators#infix_xx
# https://docs.raku.org/routine/flat

It outputs 0 which is not what was expected (1000). However, this works right

say ([1, 2] xx 5).flat.sum;

Why is behavior different? Is it due to precision?

Another thing is

my $arr = ([1e50, 1, -1e50] xx 1000);
my @array = $arr.flat;

how can I make every element of this flattened list to float efficiently?

One way I know is iterating every element of this list and calling Num method.

my $arr = [1, 2] xx 5; #([1e50, 1, -1e50] xx 10);

my @array = $arr.flat;
for @array {$_=$_.Num};
like image 952
Suman Khanal Avatar asked Dec 01 '21 13:12

Suman Khanal


1 Answers

To answer your first question: yes, it's precision, as you're forcing it to using floating point arithmetic, and the 1 is drowned out.

my @a = |(10**50, 1, -10**50) xx 1000;
say @a.sum;  # 1000

Using 10**50 allows Raku to keep using (large) integer arithmetic.

To ensure all elements in an array are floating points, you can add a coercing constraint to your array definition:

my Num() @a = |(10**50, 1, -10**50) xx 1000;
say @a.sum;  # 0, as the 1's get drowned out again
like image 79
Elizabeth Mattijsen Avatar answered Nov 15 '22 15:11

Elizabeth Mattijsen