gpt4 book ai didi

java - 使用比较器对列表进行排序后数字精度会丢失

转载 作者:行者123 更新时间:2023-12-02 04:47:24 25 4
gpt4 key购买 nike

我有一个方法,可以根据“距离”属性比较填充有 DMatch 对象的任何给定列表。我现在遇到的问题是,我从排序列表中得到的距离类似于:

Debug: MainClass -> descriptorMatcher: Min_Dist: 0.070726834
Debug: MainClass -> descriptorMatcher: Max_Dist: 0.5799786

虽然它应该是这样的:

Info: MainClass -> descriptorMatcher: Max_Dist: 0.5799785852432251
Info: MainClass -> descriptorMatcher: Min_Dist: 0.07072683423757553

为什么我会失去数字精度以及如何避免它。

代码:

public static List<DMatch> getTopGoodMatches(List<DMatch> list, int startIndx, int range) {
if (list != null) {
if (!list.isEmpty()) {

if (range != 0) {
if ( (startIndx + range) <= list.size() ){
Log.V(TAG, "getTopGoodMatches", range + " match line(s) will be drawn");
Collections.sort(list, ascOrder);
return list.subList(startIndx, (startIndx + range));
} else {
Log.E(TAG, "getTopGoodMatches", "(startIndx + range) must be <= the total list size");
return null;
}
} else {
Log.E(TAG, "main", "range can not be zero");
return null;
}

} else {
Log.E(TAG, "getTopGoodMatches", "the list you passed to this method is empty, empty list can not be sorted.");
return null;
}
} else {
Log.E(TAG, "getTopGoodMatches", "the list you passed to this method is null, null object can not be sorted.");
return null;
}
}

private static Comparator<DMatch> ascOrder = new Comparator<DMatch>() {

public int compare(DMatch arg0, DMatch arg1) {
// TODO Auto-generated method stub
return Double.compare(arg0.distance, arg1.distance);
}
};

最佳答案

如果您需要任意精度的十进制值,则不能使用 floatdouble。请改用 BigDecimal。或者将其转换为非十进制值(intlong)并注意逻辑中的小数位数。

参见http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

关于java - 使用比较器对列表进行排序后数字精度会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29556358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com