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
Your numbers are too big to fit in a double
.
Consider using BigDecimal
instead.