histogram method

List<List<num>> histogram(
  1. {bool normalize = true,
  2. int intervals,
  3. ProbabilityDensity probabilityDensity}
)

Returns an object of type List<List<num>> containing a sample histogram.

  • The first list represents the range of the sample values divided into a suitable number of intervals:(min, min + h, ... max), where h is the intervalSize. The default number of intervals is calculated using the Freedman-Diaconis rule.

  • The second list represent a count of how many sample values fall into each interval.

    • If normalize == true, the histogram count will be normalized using the factor: sampleSize * intervalSize. This is suitable when comparing the histogram to a probability distribution.
  • The third list is only added if normalized == true. It contains the probabilityDensity evaluated at each point (min, min + h, ..., max).

    • The default value of probabilityDensity is normalPdf(x, mean, stdDev), where mean is the sample mean and stdDev is the sample standard deviation.

Implementation

List<List<num>> histogram({
  bool normalize = true,
  int? intervals,
  ProbabilityDensity? probabilityDensity,
}) {
  final sampleSize = sample.length;
  // Number of intervals (Freedman-Diaconis rule).
  final optimalIntervalSize =
      2 * (quartile3 - quartile1) / sampleSize.root(3);
  intervals ??= (max - min) ~/ optimalIntervalSize;
  final intervalSize = (max - min) / intervals;
  final n = intervals + 1;
  probabilityDensity ??= (num x) => normalPdf(x, mean, stdDev);
  // final minMid = min + 0.5 * intervalSize;
  final xValues = List<num>.generate(n, (i) => min + i * intervalSize);
  final yValues = List<num>.generate(n, (_) => 0.0);

  for (final current in sample) {
    // Calculate interval index of current.
    final index = (current - min) ~/ intervalSize;
    ++yValues[index];
  }

  if (normalize) {
    for (var i = 0; i < n; ++i) {
      yValues[i] = yValues[i] / (sampleSize * intervalSize);
    }
    final pdf = List<num>.generate(
        n, (i) => probabilityDensity!(min + i * intervalSize));
    return [xValues, yValues, pdf];
  } else {
    return [xValues, yValues];
  }
}