Frequencies<T>.from constructor Null safety

Frequencies<T>.from(
  1. Iterable<T> iterable
)

Calculates frequencies of discrete items.

Uses == and hashCode for counting values.

Example

// Four samples, two cats.
final frequencies = Frequencies.from(['dog', 'cat', 'sheep', 'cat']);

print("Probability of cat: ${frequencies.pdf('cat')"); // --> 0.5

Implementation

factory Frequencies.from(Iterable<T> iterable) {
  final result = <T, double>{};

  // Count relative frequencies of items and sum of relative frequencies
  var n = 0;
  for (var item in iterable) {
    result[item] = (result[item] ?? 0.0) + 1.0;
    n++;
  }

  // Normalize values (so the sum is 1.0).
  for (var entry in result.entries) {
    result[entry.key] = entry.value / n.toDouble();
  }

  return Frequencies._(result);
}