2

你能帮我解决这个问题吗.. 我正在尝试获取一个大十进制 (BigDecimal) 的日志,但我在下面收到一条异常错误消息:

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

`

4

2 回答 2

3

看起来 hitDocuments 或 totalDocuments(或两者)是 Double,而 hitDocuments 是 0.0。任何东西 / 0.0 = Double.Infinity(如果 totalDocuments 为 0.0,则为 NaN)。也不能取日志。

于 2013-01-17T01:55:18.417 回答
2

如果num是,0那么Math.log()将返回Infinite

如果参数是正或负,则结果为负无穷大

于 2013-01-17T01:54:19.867 回答