average property

double get average

The arithmetic mean of the elements of a non-empty iterable.

The arithmetic mean is the sum of the elements divided by the number of elements. This method is specialized for integers, and may give a different result than IterableNumberExtension.average for the same values, because the the number algorithm converts all numbers to doubles.

The iterable must not be empty.

Implementation

double get average {
  var average = 0;
  var remainder = 0;
  var count = 0;
  for (var value in this) {
    // Invariant: Sum of values so far = average * count + remainder.
    // (Unless overflow has occurred).
    count += 1;
    var delta = value - average + remainder;
    average += delta ~/ count;
    remainder = delta.remainder(count);
  }
  if (count == 0) throw StateError('No elements');
  return average + remainder / count;
}