Reputation: 5182
I'm trying to figure a problem out with BigDecimal. My code:
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));
What I'd like to do is: emotionCountSentenceBig/(emotionCountBig*tweetcount)
(The values can be bigger)
If i try this I get a zero, which is not possible. Any help ?
Upvotes: 0
Views: 107
Reputation: 328588
You need to specify the MathContext for the division too:
emotionCountSentenceBig.divide(tweetcount.multiply(emotionCountBig, mc), mc);
That gives the expected result:
2.969226352632111794036880818610913852084810652372969382467557947E-8
Now as rightly commented by @PeterLawrey you could use doubles instead:
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);
}
which prints:
result = 2.9692263526321117E-8
Note that if you use:
double result = 84988 / (3344048 * 855937);
you are actually doing your operations (* and /) on integer and it will return 0. You can prevent it by explicitly using a double, for example (note the d
):
double result = 84988d / (3344048d * 855937);
Upvotes: 4
Reputation: 533472
I would use double
int tweetcount = 3344048;
int emotionCountBig = 855937;
int emotionCountSentenceBig = 84988;
double pmi = emotionCountSentenceBig/((double) tweetcount * emotionCountBig);
System.out.println(pmi);
prints
2.9692263526321117E-8
which is close to the answer using BigDecimal
2.969226352632111794036880818610913852084810652372969382467557947E-8
Upvotes: 2