On Mar 13, 5:57 pm, "Prime" <(E-Mail Removed)> wrote:

> Is there any particular reason(s) why I should use the

> Double.compare() method?
I'll answer that but for a start: you probably, as Daniel noted,

do *not* want to directly compare double. At least, if you ask

the question, you probably do not know all the details involved.

You probably want to read this (and want to learn what an

epsilon, in this context, is):

http://docs.sun.com/source/806-3568/ncg_goldberg.html
Now to answer your question...

>

> (i.e. Double.compare(<double1>, <double2>) == 0, instead of just

> saying double1 == double2 ??)
What are double1 and double2? Objects? Primitives? What Java version?

Can auto-boxing take place?

final Double a = new Double( 0.1d );

final Double b = new Double( 0.1d );

System.out.println( "a == b ? " + (a == b) );

System.out.println( "Double.compare(a,b) == 0: " +

(Double.compare(a,b) == 0) );

final double c = 0.1d;

final double d = 0.1d;

System.out.println( "c == d ? " + (c == d) );

System.out.println( "Double.compare(c,d) == 0: " +

(Double.compare(c,d) == 0) );

Will output:

a == b ? false

Double.compare(a,b) == 0: true

c == d ? true

Double.compare(c,d) == 0: true

When you compare a and b with == you're comparing the

references of the two objects. As I specifically used

"new" to construct them, the JVM MUST (by the specs)

create two different objects. Hence a == b returns false

(the references are not pointing to the same object).

When you compare c and d with ==, you're comparing

primitives.

Now, a little more fun:

final double e = 0.1d;

final double f = 0.3d;

final double g = 0.2d;

final double h = f - g; // we're substracting 0.2 to 0.3 or

are we?

System.out.println( "h == e ? " + (h == e) );

System.out.println( "e is " + e );

System.out.println( "h is " + h );

will output:

h == e ? false

e is 0.1

h is 0.09999999999999998

And the fact Java actually does output "e is 0.1" is really

interesting (hint: just as most decimal numbers, it's

impossible to represent 0.1 using Java's floating point numbers).