在 Dart 中查找列表 <int> 的中位数

Find the Median of a list<int> in Dart

我有一个整数列表,其中包含以毫秒为单位的时间(例如 1433、834、1020..)。我需要计算中位数。我开发了以下代码,但与我在 Excel 中计算的中位数相比,我得到的中位数是完全错误的。有任何想法吗?有什么 Dart/flutter 库可以用来做统计吗?

  /// Calculate median
  static int calculateMedian(TimeRecordNotifier timeRecordNotifier) {
    List<int> mList = List();
    timeRecordNotifier.timeRecords.forEach((element) {
      mList.add(element.partialTime);
    });

    //clone list
    List<int> clonedList = List();
    clonedList.addAll(mList);

    int median;
    //sort list
    clonedList.sort((a, b) => a.compareTo(b));

    if (clonedList.length == 1)
      median = mList[clonedList.length - 1];
    else if (clonedList.length % 2 == 1)
      median = mList[(((clonedList.length) / 2) - 1).round()];
    else {
      int lower = mList[((clonedList.length ~/ 2) - 1)];
      int upper = mList[(clonedList.length ~/ 2)];
      median = ((lower + upper) / 2.0).round();
    }

    return median;
  }

在以下数据集上,预期中值为 901,5,但是该算法给出了 461

131
144
203
206
241
401
415
427
439
439
452
455
456
469
471
471
483
483
491
495
495
502
505
512
521
522
523
547
551
561
610
727
745
777
790
793
892
911
924
943
957
977
978
989
992
1008
1024
1039
1070
1074
1092
1115
1139
1155
1159
1174
1176
1194
1203
1208
1227
1228
1248
1270
1271
1272
1273
1276
1284
1290
1294
1439
1740
1786

我使用 NumDart implementation 重构了代码,现在可以使用了。感谢@MartinM 的评论!

/// Calculate median
  static int calculateMedian(TimeRecordNotifier timeRecordNotifier) {
    List<int> mList = List();
    timeRecordNotifier.timeRecords.forEach((element) {
      mList.add(element.partialTime);
    });

    //clone list
    List<int> clonedList = List();
    clonedList.addAll(mList);

    //sort list
    clonedList.sort((a, b) => a.compareTo(b));

    int median;

    int middle = clonedList.length ~/ 2;
    if (clonedList.length % 2 == 1) {
      median = clonedList[middle];
    } else {
      median = ((clonedList[middle - 1] + clonedList[middle]) / 2.0).round();
    }

    return median;
  }