我正在尝试找出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正确评论的那样,您可以改用双打:

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);
}


打印:


  结果= 2.9692263526321117E-8


请注意,如果您使用:

double result = 84988 / (3344048 * 855937);


您实际上是在对整数执行操作(*和/),并且它将返回0。例如,可以通过显式使用double来防止出现这种情况(请注意d):

double result = 84988d / (3344048d * 855937);

10-07 13:23
查看更多