Java 使用比较器对列表排序后,数字精度将丢失

Java 使用比较器对列表排序后,数字精度将丢失,java,precision,comparator,Java,Precision,Comparator,我有一个方法,可以根据“距离”属性比较任何给定的填充了DMatch对象的列表。现在的问题是,我从排序列表中得到的距离是这样的: Debug: MainClass -> descriptorMatcher: Min_Dist: 0.070726834 Debug: MainClass -> descriptorMatcher: Max_Dist: 0.5799786 虽然它应该是这样的: Info: MainClass -> descriptorMatcher: Max_Dis

我有一个方法,可以根据“距离”属性比较任何给定的填充了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);
    }
};
公共静态列表getTopGoodMatches(列表列表,int-startIndx,int-range){
如果(列表!=null){
如果(!list.isEmpty()){
如果(范围!=0){

如果((startIndx+range)如果需要具有任意精度的十进制值,则不能使用
float
double
。请改用
BigDecimal
。或者将其转换为非十进制值(
int
long
),并注意逻辑中的十进制位数


请参见

我不知道为什么不允许使用BigDecimal?每次我使用它时,eclipse都会用红色突出显示它,并建议将其转换为float?有什么想法吗?BigDecimal是一个类。因此,您不能使用标准运算符来执行操作。因此,您必须使用+而不是-。减等等。请阅读BigDecimal的javadoc,但将其作为y您可以看到,在上面发布的比较器方法中,我没有-or+,当我使用BigDecimal.compare时……我收到错误如果比较方法出现问题,您必须将“返回Double.compare(arg0.distance,arg1.distance);”替换为“返回arg0.distance.compareTo(arg1.distance);”