我正在尝试解决 BigDecimal 的问题。我的代码:
BigDecimal tweetcount = new BigDecimal(3344048);
BigDecimal emotionCountBig = new BigDecimal(855937);
BigDecimal emotionCountSentenceBig = new BigDecimal(84988);
MathContext mc = new MathContext(64);
PMI[cnt] = (emotionCountSentenceBig.divide((tweetcount.multiply(emotionCountBig,mc)),RoundingMode.HALF_UP));
我想做的是:emotionCountSentenceBig/(emotionCountBig*tweetcount)
(数值可以更大)
如果我尝试这样做,我会得到零,这是不可能的。有什么帮助吗?
最佳答案
您还需要指定除法的 MathContext:
emotionCountSentenceBig.divide(tweetcount.multiply(emotionCountBig, mc), mc);
这给出了预期的结果:
2.969226352632111794036880818610913852084810652372969382467557947E-8
现在,正如 @PeterLawrey 正确评论的那样,您可以使用 double 来代替:
public static void main(String[] args) throws Exception {
double tweetcount = 3344048;
double emotionCount = 855937;
double emotionCountSentence = 84988;
double result = emotionCountSentence / (tweetcount * emotionCount);
System.out.println("result = " + result);
}
打印:
result = 2.9692263526321117E-8
请注意,如果您使用:
double result = 84988 / (3344048 * 855937);
您实际上是在对整数进行运算(* 和/),它将返回 0。您可以通过显式使用 double 来阻止它,例如(注意 d
):
double result = 84988d / (3344048d * 855937);
关于java - 使用 bigdecimal 进行数学运算,结果为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13682254/