Let's say I have two arrays of double. I've been experimenting with Stream from Java 8. I think I've understood the main ideas but then I realised that I'm not sure how to manipulate two Streams at the same time.
For example, I want to calculate the covariance of both arrays.
public class foo {
public static double mean(double[] xs) {
return Arrays.stream(xs).average().getAsDouble();
}
public static void main(String[] args) {
double[] xs = {1, 2, 3, 4, 5, 6, 7, 8, 9};
double[] ys = {1517.93, 1757.78, 1981.1, 2215.73, 2942.66, 3558.32, 4063.91, 4521.16, 5101.76, 5234.12};
System.out.println("Mean of xs: " + mean(xs));
double xs_sumDeviation = Arrays.stream(xs)
.boxed()
.mapToDouble(d -> d.doubleValue() - mean(xs))
.sum();
// Covariance
double covXY = Arrays.stream(xs, ys)
.mapToDouble(x,y -> {
double numerator = (x-mean(xs)* (y-mean(ys);
double denominator = Math.sqrt((x-mean(xs)* (x-mean(xs));
return numerator / denominator;
})
.sum();
}
}
Thank you for suggestions.
Attempt 1.
public static double covariance(double[] xs, double[] ys) {
double xmean = mean(xs);
double ymean = mean(ys);
double numerator = IntStream.range(0, Math.min(xs.length, ys.length))
.parallel()
.mapToDouble(i -> (xs[i] - xmean) * (ys[i] - ymean))
.sum();
double denominator = Math.sqrt(IntStream.range(0, xs.length)
.parallel()
.mapToDouble(i -> (xs[i] - xmean) * (xs[i] - xmean))
.sum());
return numerator / denominator;