8

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};
Suman Khanal
  • 3,079
  • 1
  • 17
  • 29
  • You can make `[1e50, 1, -1e50]` be three floats by writing it as `[1e50, 1e0, -1e50]`. (I imagine you're asking about variables, not literals, and that most readers will know or be able to guess what I've noted, but I thought I'd comment just in case.) – raiph Dec 01 '21 at 22:34

1 Answers1

8

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
Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105