mannWhitneyP function

double? mannWhitneyP(
  1. List<double> a,
  2. List<double> b
)

The two-sided p-value of a Mann-Whitney U test: the probability of seeing a difference at least this large between a and b if both came from the same distribution.

A small value (below 0.05, say) means the samples differ significantly. The test compares ranks, so it does not assume a normal distribution, and a few outliers barely change the result. It uses the normal approximation with tie and continuity corrections.

Returns null when either list has fewer than 3 samples, which is too few for any result to be significant.

Implementation

double? mannWhitneyP(List<double> a, List<double> b) {
  final n1 = a.length;
  final n2 = b.length;
  if (n1 < 3 || n2 < 3) return null;

  final values = [
    for (final x in a) _Ranked(x, true),
    for (final x in b) _Ranked(x, false),
  ]..sort((p, q) => p.value.compareTo(q.value));

  final n = n1 + n2;
  var rankSumA = 0.0;
  var tieSum = 0.0;
  for (var i = 0; i < n;) {
    var j = i + 1;
    while (j < n && values[j].value == values[i].value) {
      j++;
    }
    final rank = (i + 1 + j) / 2; // average of ranks i+1 .. j
    for (var k = i; k < j; k++) {
      if (values[k].first) rankSumA += rank;
    }
    final t = (j - i).toDouble();
    tieSum += t * t * t - t;
    i = j;
  }

  final u = rankSumA - n1 * (n1 + 1) / 2;
  final mean = n1 * n2 / 2;
  final variance = n1 * n2 / 12 * ((n + 1) - tieSum / (n * (n - 1)));
  if (variance <= 0) return 1;
  final z = ((u - mean).abs() - 0.5) / math.sqrt(variance);
  if (z <= 0) return 1;
  return _erfc(z / math.sqrt2);
}