Question

I want to calculate Naive Bayes probability. The calculation is :

Math.Log((n1+1)/(n2+n3))/Math.Log(2)

The result should be in double, where n1..n3 are long. How do I cast it?

My current cast like this

Math.Log((double)(n1+1)/(n2+n3))/Math.Log(2)
Était-ce utile?

La solution

Your current cast will work correctly. If either of the operands of the division is a double, the other will be cast to a double too.

See the Java Language Specification on Binary Numeric Promotion:

Widening primitive conversion is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top