【问题标题】:Find the Median of a list<int> in Dart在 Dart 中查找列表<int> 的中位数
【发布时间】:2020-12-01 18:36:05
【问题描述】:

我有一个整数列表,其中包含以毫秒为单位的时间(例如 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

【问题讨论】:

标签: flutter dart statistics median


【解决方案1】:

我使用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;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-10
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2016-09-23
    • 2021-06-12
    相关资源
    最近更新 更多