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};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With