Domanda

Here is my code:

Real AB = adj[a].get(b);
System.out.println("AB " + AB);
Real AC = adj[a].get(c);
System.out.println("AC " + AC);
Real BC = adj[b].get(c);
System.out.println("BC " + BC);
System.out.println(AB.plus(BC));
System.out.println(AB.plus(BC).equals(AC));

And here is the output:

AB 2.2360679775
AC 6.7082039325
BC 4.4721359550
6.7082039325
false

Even though the numbers are identical, why does it return false? I have also tried

System.out.println(AB.plus(BC).compareTo(AC) == 0);

Again, false.

È stato utile?

Soluzione

The equals() implementation for Real checks for identical significand, error and exponent. Instead, use approximates(), which "takes into account possible errors (e.g. numeric errors)."

Addendum: See also these articles as regards floating point comparison:

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top