Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of two double numbers in java is infinity

The sum of two double is infinity even though these numbers are not infinity. The code is following.

entropy += (probs.get(key)* (Math.log(probs.get(key)) / Math.log(2.0)));
    if(entropy == Double.POSITIVE_INFINITY || entropy == Double.NEGATIVE_INFINITY){
        System.out.println("Prob:"+probs.get(key));
        System.out.println("base 10: "+Math.log(probs.get(key)));
        System.out.println("base 2: "+Math.log(2.0));
        System.out.println("result: "+(probs.get(key)*(Math.log(probs.get(key))) / Math.log(2.0)));
        System.out.println("entropy before sum "+temp);
        break;
    }`

And the result is:

Prob:1.0476603084695572E305
base 10: 702.3350127634005
base 2: 0.6931471805599453
result: 1.0615472972511642E308
entropy before sum: 1.246498306457423E308

So how can it be possible that the sum of

result + entropy = 1.0615472972511642E308 + 1.246498306457423E308 = INFINITY

like image 604
user1914367 Avatar asked Dec 27 '13 15:12

user1914367


1 Answers

Your numbers are too big to fit in a double.
Consider using BigDecimal instead.

like image 119
SLaks Avatar answered Sep 24 '22 22:09

SLaks