2013-01-17 17 views
2

你能幫我在這一個傢伙..我想獲得一個大十進制日誌(BigDecimal),但我得到一個異常錯誤消息如下:異常在線程「主」java.lang.NumberFormatException:無限或NaN

Exception in thread "main" java.lang.NumberFormatException: Infinite or NaN 

這是我有:

BigDecimal num = new BigDecimal(totalDocuments/hitDocuments); 
BigDecimal idf = new BigDecimal(Math.log(num.doubleValue())); 
BigDecimal termF = new BigDecimal(terms.get(j).getTermFreq()); 
BigDecimal tfIdf = new BigDecimal(termF.doubleValue() * idf.doubleValue()); 
terms.get(j).setTfIdf(tfIdf.doubleValue()); 

我得到第二行除外;我如何解決這個問題?非常感謝你的好意。哦,順便說一句,我正在試圖計算文本文件的「tf-idf」。

下面是完整的代碼

File[] corpus = new File("files//").listFiles(); int totalDocuments = (corpus.length) - 1; //-1 for the suspect document.

int hitDocuments = 1; 
    for (int i = 0; i < corpus.length; i++) { 
     ArrayList<String> corpusWords = getWords(corpus[i].getAbsolutePath()); 
     for (int j = 0; j < terms.size(); j++) { 
      for (int k = 0; k < corpusWords.size(); k++) { 
       if (terms.get(j).getTerm().equals(corpusWords.get(k))) { 
        hitDocuments++; 
       } 
      } 
      //Update the tf-idf 
      BigDecimal num = new BigDecimal(totalDocuments/hitDocuments); 
      BigDecimal idf = new BigDecimal(Math.log(num.doubleValue())); 
      BigDecimal termF = new BigDecimal(terms.get(j).getTermFreq()); 
      BigDecimal tfIdf = new BigDecimal(termF.doubleValue() * idf.doubleValue()); 
      terms.get(j).setTfIdf(tfIdf.doubleValue()); 
     } 
    } 

`

回答

1

如果num0然後Math.log()將返回Infinite

如果參數爲正數或負數,則結果爲負數無窮大

+0

嗨,感謝您的快速響應,但沒有辦法num可以爲零,因爲變量'totalDocuments'的長度爲'corpusFiles.listFiles.length'。而變量'hitDocuments'默認值爲1。再次感謝 –

+0

我已經修復了一個想法,我從你的答覆中得到了..我已經重新初始化變量'hitDocuments = 1;'..謝謝 –

2

看起來像hitDocuments或totalDocuments(或兩者)是Double,並且hitDocuments爲0.0。任何/ 0.0 = Double.Infinity(如果totalDocuments爲0.0,則爲NaN)。無法取兩者的日誌。

+0

我已經編輯了原文,我已經添加完整的代碼.. –

相關問題