Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java's Stream.reduce() to calculate sum of powers gives unexpected result

List<Integer> list = Arrays.asList(1, 2, 3);

int i = list.stream().mapToInt(e -> e)
            .reduce((x, y) -> (int) Math.pow(x, list.size()) + (int) Math.pow(y, list.size()))
            .getAsInt();
        System.out.println(i);

The result of this operation should be 1*1*1 + 2*2*2 + 3*3*3 = 36. But instead I get i = 756. What's wrong? What should I change in order reduce() to work correctly?

like image 761
sva605 Avatar asked Oct 14 '16 10:10

sva605


2 Answers

The solution was already posted, but you get 756,

because the first call to reduce (x,y) with (1,2) is

1^3+2^3=9

then you reduce with (x,y) with (9,3)

9^3+3^3=756

BTW, since exponentiation is not associative, you can also get other values. For example, when using a parallel stream, I also got 42876 as result.

like image 139
user140547 Avatar answered Oct 12 '22 13:10

user140547


You don't even need to reduce

List<Integer> list = Arrays.asList(1, 2, 3);

int i = list.stream()
         .mapToInt(e -> (int) Math.pow(e, list.size()))
         .sum();
like image 42
Ash Avatar answered Oct 12 '22 13:10

Ash