2012-12-03 59 views
0

我想用BigDecimal來解決問題。我的代碼:數學大結果爲0

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)

(該值可以更大)

如果我試試這個,我得到一個零,這是不可能的。任何幫助?

+1

我懷疑的答案,您所建模是不準確的更多的小數位,更不用說了16.我建議我們代之以'double'類型。 –

+0

可能是,但乘法得到的數字對於雙倍來說太大了。有沒有辦法解決這個問題? – Ojtwist

+1

@Ojtwist我懷疑它 - 你可能正在做一個整數乘法。 – assylias

回答

4

你需要指定的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); 
+0

我怎樣才能得到這個價值?因爲如果我調試,我看到的唯一值是intCompact,這是不正確的。 – Ojtwist

+0

intCompact是什麼?我只是複製了我提出的修改後的代碼,並將結果以「main」方法打印並運行該程序。 – assylias

+0

是的,我可以看到它時,我打電話給tostring,thx – Ojtwist

2

我會用double

int tweetcount = 3344048; 
int emotionCountBig = 855937; 
int emotionCountSentenceBig = 84988; 

double pmi = emotionCountSentenceBig/((double) tweetcount * emotionCountBig); 
System.out.println(pmi); 

打印

2.9692263526321117E-8 

這是接近使用的BigDecimal

2.969226352632111794036880818610913852084810652372969382467557947E-8