如何计算方差?

时间:2019-10-07 21:31:26

标签: java arrays iterator variance

如何使用迭代器计算方差?

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);
    }

1 个答案:

答案 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);

}