chris01
chris01

Reputation: 12331

Java: Compare Double 0 with Min/Max

I try to compare Doubles Min/Max with 0.0.

Double min = Double.MIN_VALUE;
Double max = Double.MAX_VALUE;

Double d = new Double (0.0);

System.out.println (min < d);
System.out.println (min.compareTo (d) < 0);

System.out.println (d < max);
System.out.println (d.compareTo (max) < 0);

I would expect all output to be true.

But instead I get

false
false
true
true

Why?

Upvotes: 2

Views: 186

Answers (2)

xenteros
xenteros

Reputation: 15842

The issue is related to IEEE-754. In fact, Double.MIN_VALUE is equal to machine-epsilon which is the number represented by 0.00000...00. The smallest double possible should be referred as

-Double.MAX_VALUE.

Upvotes: 1

Jesper
Jesper

Reputation: 206816

Look at the documentation of Double.MIN_VALUE, which says:

A constant holding the smallest positive nonzero value of type double, 2-1074.

So this is a value larger than 0, which is why you 'false' if you check if it's smaller than zero.

Upvotes: 6

Related Questions