gpt4 book ai didi

java - 在计算信息增益时显示 NaN 作为输出的双变量数组

转载 作者:行者123 更新时间:2023-12-01 20:00:10 25 4
gpt4 key购买 nike

我一直在尝试用 Java 编写一个程序来计算属性的信息增益,前提是它具有不同的值和所有其他所需的值。以下是我的程序

package dwdmp5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
*
* @author Gaurav
*/
public class Dwdmp5 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

double P,N,IGtotal;
System.out.println("How many total P values?");
P = Double.parseDouble(br.readLine());
System.out.println("How many total N values?");
N = Double.parseDouble(br.readLine());
IGtotal = ((-1)*(P/(P+N))*((Math.log(P/(P+N)))/Math.log(2))) + ((-1)*(N/(P+N))*((Math.log(N/(P+N)))/Math.log(2)));
System.out.println("Overall Information gain = "+IGtotal);
int numV;
System.out.println("How many distinct values of an attribute?");
numV = Integer.parseInt(br.readLine());
double [] p = new double[numV];
double [] n = new double[numV];
double [] ig = new double[numV];
int i,temp=0;
System.out.println("Enter pi for all attributes");
for(i=0;i<numV;i++)
p[i] = Integer.parseInt(br.readLine());
System.out.println("Enter ni for all attributes");
for(i=0;i<numV;i++)
n[i] = Integer.parseInt(br.readLine());
System.out.println("Attribute\tpi\tni\tI(pi,ni)");
for(i=0;i<numV;i++)
{ temp = i;
ig[i] = ((-1)*(p[i]/(p[i]+n[i]))*((Math.log(p[i]/(p[i]+n[i])))/Math.log(2))) + ((-1)*(n[i]/(p[i]+n[i]))*((Math.log(n[i]/(p[i]+n[i])))/Math.log(2)));

System.out.println("attrib"+(temp+1)+"\t\t"+p[i]+"\t\t"+n[i]+"\t\t"+ig[i]);
}


}

}

它应该计算个人信息增益并以表格格式显示它们。但这是当我输入 pini 的值之一作为 0

时得到的输出
run:
How many total P values?
9
How many total N values?
5
Overall Information gain = 0.9402859586706309
How many distinct values of an attribute?
3
Enter pi for all attributes
2
4
3
Enter ni for all attributes
3
0
2
Attribute pi ni I(pi,ni)
attrib1 2.0 3.0 0.9709505944546686
attrib2 4.0 0.0 NaN
attrib3 3.0 2.0 0.9709505944546686
BUILD SUCCESSFUL (total time: 17 seconds)

程序没有显示任何错误。使用科学计算器计算相同的值会显示正确的答案。请帮我解决这个问题。

最佳答案

JLS (Java 语言规范)规定:

A floating-point operation that has no mathematically definite result produces NaN.

All numeric operations with NaN as an operand produce NaN as a result.

现在,当您阅读 Math.log(double) 上的 JavaDoc 时你会看到这个:

If the argument is positive zero or negative zero, then the result is negative infinity.

如果您查看一下计算结果,您会发现,对于 p = 4 且 n = 0,您最终会得到 0.0 * Math.log( 0.0/(4.0 + 0.0) ) => 0.0 * Math.log(0.0) => 0.0 * -Infinity => NaN

根据 JLS 定义的规则,其余计算将产生 NaN。

为什么0.0 * -Infinity不等于0?看看这里:https://math.stackexchange.com/questions/28940/why-is-infinity-multiplied-by-zero-not-an-easy-zero-answer

关于java - 在计算信息增益时显示 NaN 作为输出的双变量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48261453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com