forked from KNEMC/KLALB
把NTP从平均数改成中位数,防止极端值干扰
This commit is contained in:
@@ -5,6 +5,9 @@ import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.kne.math.Long128;
|
||||
|
||||
@@ -256,4 +259,27 @@ public class NTPTimestamps {
|
||||
.setBit(63);
|
||||
}
|
||||
}
|
||||
|
||||
public static Long128 median(List<Long128> values) {
|
||||
Objects.requireNonNull(values);
|
||||
if ( values.isEmpty()) {
|
||||
throw new IllegalArgumentException("列表不能为空");
|
||||
}
|
||||
|
||||
// 1. 创建副本并排序
|
||||
List<Long128> sorted = new ArrayList<>(values);
|
||||
sorted.sort(Long128::compareTo);
|
||||
|
||||
// 2. 计算中位数
|
||||
int size = sorted.size();
|
||||
if (size % 2 == 1) {
|
||||
// 奇数个:取中间值
|
||||
return sorted.get(size / 2);
|
||||
} else {
|
||||
// 偶数个:取中间两个的平均值
|
||||
Long128 left = sorted.get(size / 2 - 1);
|
||||
Long128 right = sorted.get(size / 2);
|
||||
return left.add(right).divide(Long128.valueOf(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user