Pregunta

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

¿Fue útil?

Solución

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

Otros consejos

Use BigDecimalinstead of Double Because of BigDecimal consists of an arbitrary precision integer unscaled value & 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10-scale).

Read more:http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top