如何使用迭代器计算方差?
public static double variance(final Iterator<Integer> array) {
}
-此方法计算平均值
private static double mean(final List<Integer> array) {
return array.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(Double.NaN);
}
答案 0 :(得分:0)
基于此answer,您可以执行以下操作:
public static double variance(final Iterator<Integer> iterator) {
List<Integer> array = new ArrayList<>();
iterator.forEachRemaining(array::add);
double mean = mean(array);
double temp = 0;
for(double a :array)
temp += (a-mean)*(a-mean);
return temp/(array.size()-1);
}
但是奇怪的是在mean
中使用了List
。如果不需要Iterator
,则可以:
public static double variance(final List<Integer> array) {
double mean = mean(array);
double temp = 0;
for(double a :array)
temp += (a-mean)*(a-mean);
return temp/(array.size()-1);
}
使用stream
public static double variance(final Iterator<Integer> iterator) {
List<Integer> array = new ArrayList<>();
iterator.forEachRemaining(array::add);
double mean = mean(array);
return array.stream()
.map(a -> (a-mean)*(a-mean))
.reduce(0d, Double::sum)/(array.size()-1);
}