相关疑难解决方法(0)

为什么Java的Double.compare(double,double)实现方式如何呢?

我正在研究Java标准库(6)中compare(double,double)的实现.它写道:

public static int compare(double d1, double d2) {
    if (d1 < d2)
        return -1;       // Neither val is NaN, thisVal is smaller
    if (d1 > d2)
        return 1;        // Neither val is NaN, thisVal is larger

    long thisBits = Double.doubleToLongBits(d1);
    long anotherBits = Double.doubleToLongBits(d2);

    return (thisBits == anotherBits ?  0 : // Values are equal
            (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
             1));                          // (0.0, -0.0) or (NaN, !NaN)
}
Run Code Online (Sandbox Code Playgroud)

这个实现的优点是什么?


编辑:"优点"是一个(非常)糟糕的选择.我想知道它是如何工作的.

java floating-point comparison

35
推荐指数
2
解决办法
5万
查看次数

Java错误:"比较方法违反了其总合同!"

我有这个代码:

package org.optimization.geneticAlgorithm;
import org.optimization.geneticAlgorithm.selection.Pair;

public abstract class Chromosome implements Comparable<Chromosome> {
    public abstract double fitness();
    public abstract Pair<Chromosome> crossover(Chromosome parent);
    public abstract void mutation();
    public int compareTo(Chromosome o) {
        int rv = 0;
        if (this.fitness() > o.fitness()) {
            rv = -1;
        } else if (this.fitness() < o.fitness()) {
            rv = 1;
        }
        return rv;
    }
}
Run Code Online (Sandbox Code Playgroud)

每次我运行此代码时,我都会收到此错误:

Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.ComparableTimSort.mergeHi(ComparableTimSort.java:835)
at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:453)
at java.util.ComparableTimSort.mergeCollapse(ComparableTimSort.java:376)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:182)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at …
Run Code Online (Sandbox Code Playgroud)

java openjdk comparable

11
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×2

comparable ×1

comparison ×1

floating-point ×1

openjdk ×1