java - 使用 bigdecimal 进行数学运算,结果为 0

标签 java precision

我正在尝试解决 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/

相关文章:

java - 导入javax.xml.xpath无法解析

java - 如何使用 Intent 打开用户的个人资料联系人?

c++ - 在 C++ 中没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?

javascript - Math.random 产生多少熵?

java - 双哈希常数 5?

java - 如何让文字填满整行TextView?

java - 定位推送通知

python - 在 python 中,为什么 math.floor(4.9999999999999999) == 5?

java - 在不损失精度的情况下划分两个数字

php - MySQL 中的 float 不正确