Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #202 Sum of squares

Calculate the sum of squares s of data, an array of floating point values.

import java.util.Arrays;
double s = Arrays.stream(data).map(i -> i * i).sum();

data has type double[]
import static java.util.stream.DoubleStream.of;
double s = of(data).map(x -> x * x).sum();
import static java.util.stream.DoubleStream.of;
import java.math.BigDecimal;
BigDecimal s = of(data)
    .mapToObj(String::valueOf)
    .map(BigDecimal::new)
    .map(x -> x.multiply(x))
    .reduce(BigDecimal::add)
    .get();
(defn square [x] (* x x))

(def s (reduce + (map square data)))

New implementation...
< >
Bart