Comparing numbers

I have the following lines in a code:

System.out.println(9000000000000000d == 9000000000000001d);

System.out.println(90000000000000000d == 90000000000000001d);

The results are:

false

true

That's strange... someone knows why this happen ? And how can I compare big numbers like this correctly ?

[337 byte] By [dragzula] at [2007-11-26 13:18:47]
# 1
Maybe it's out of doubles range of numbers.Try using java.math.BigDecimal or BigInteger.
Sasa_Ivanovica at 2007-7-7 17:44:34 > top of Java-index,Java Essentials,Java Programming...
# 2
google for java floating point inaccuracy.
hunter9000a at 2007-7-7 17:44:34 > top of Java-index,Java Essentials,Java Programming...
# 3

In double range, the number is, but even using BigDecimal, that's what happened:

BigDecimal a = new BigDecimal(90000000000000000d);

BigDecimal b = new BigDecimal(90000000000000001d);

System.out.println(a.equals(b));

The result is:

true

I'll take a look for "java floating point innacuracy"... anyway, I'll be waiting if I'll get an answer by here.

dragzula at 2007-7-7 17:44:34 > top of Java-index,Java Essentials,Java Programming...
# 4
>> BigDecimal a = new BigDecimal(90000000000000000d);Take out the "d"?Nope that didnt work.Are those meant to be integers or did you leave out the decimal?
TuringPesta at 2007-7-7 17:44:34 > top of Java-index,Java Essentials,Java Programming...
# 5

> In double range, the number is, but even using

> BigDecimal, that's what happened:

>

> BigDecimal a = new BigDecimal(90000000000000000d);

> BigDecimal b = new BigDecimal(90000000000000001d);

> System.out.println(a.equals(b));

>

> The result is:

>

> true

That's because you're still using doubles in the constructor. Use the BigDecimal constructor that takes a String instead, then you obviate length limitations.

Mr_Evila at 2007-7-7 17:44:34 > top of Java-index,Java Essentials,Java Programming...
# 6

If I'll take out the "d", it'll be out of range.

But what I wan't is compare double numbers, and big numbers, really. I've put BigDecimal after indications. If it works, I'll find a way. If I use String, maybe it'll work, but I don't know... I'm looking for some performance, because I want to compare and calculate numbers bigger than the range of Long, so, I'll try to find another way.

If there's no other, I'll pass a String... thanks everybody !!

dragzula at 2007-7-7 17:44:34 > top of Java-index,Java Essentials,Java Programming...