Java Reference
In-Depth Information
System
.
out
.
println
(
da
+
" != "
+
db
);
}
System
.
out
.
println
(
"NaN prints as "
+
Double
.
NaN
);
// Show that comparing two NaNs is not a good idea:
double
double
nan1
=
Double
.
NaN
;
double
double
nan2
=
Double
.
NaN
;
iif
(
nan1
==
nan2
)
System
.
out
.
println
(
"Comparing two NaNs incorrectly returns true."
);
else
else
System
.
out
.
println
(
"Comparing two NaNs correctly reports false."
);
iif
(
new
new
Double
(
nan2
)))
System
.
out
.
println
(
"Double(NaN).equals(NaN) correctly returns true."
);
new
Double
(
nan1
).
equals
(
new
else
else
System
.
out
.
println
(
"Double(NaN).equals(NaN) incorrectly returns false."
);
}
/** Compare two doubles within a given epsilon */
public
public static
static
boolean
boolean
equals
(
double
double
a
,
double
double
b
,
double
double
eps
) {
iif
(
a
==
b
)
return
true
;
// If the difference is less than epsilon, treat as equal.
return
return true
return
Math
.
abs
(
a
-
b
) <
eps
;
}
/** Compare two doubles, using default epsilon */
public
public static
static
boolean
boolean
equals
(
double
double
a
,
double
double
b
) {
return
return
equals
(
a
,
b
,
EPSILON
);
}
}
Note that neither of the
System.err
messages about “incorrect returns” prints. The point of
this example with
NaN
s is that you should always make sure values are not
NaN
before en-
trusting them to
Double.equals()
.
Rounding Floating-Point Numbers
Problem
You need to round floating-point numbers to integers or to a particular precision.