我在我的项目中使用 EJML 库。我编写了一个计算 SimpleMatrix 行 vector 方差的方法。在某些时候,我注意到在将等元 vector 传递给此方法时,我得到的方差 > 0.0。
我写这篇文章是为了进一步调查,惊讶地发现最后一行打印了 false,尽管之前的打印没有产生任何输出。
// rowVec is a 1xn SimpleMatrix of equal double elements
double one = rowVec.get(0);
for (int i = 0; i < rowVec.getNumElements(); i++) {
if (rowVec.get(i) - one != 0 || rowVec.get(i) != one) {
System.out.println(rowVec.get(i)); // no output here
}
}
// why false below???
System.out.println(one == (rowVec.elementSum() / rowVec.getNumElements()));
// why true below???
System.out.println(one*rowVec.getNumElements() < rowVec.elementSum());
有人可以解释为什么等元素 vector 的平均值大于其中一个元素吗?
跟进:解决了我的问题:
/**
* Calculates the variance of the argument matrix rounding atoms to the 10th
* significant figure.
*/
public static double variance(SimpleMatrix m) {
Preconditions.checkArgument(m != null, "Matrix argument is null.");
Preconditions.checkArgument(m.getNumElements() != 0, "Matrix argument empty.");
if (m.getNumElements() == 1) return 0;
double mean = m.elementSum() / m.getNumElements();
double sqDiviations = 0;
for (int i = 0; i < m.getNumElements(); i++) {
sqDiviations += Math.pow(decimalRoundTo(mean - m.get(i), 10), 2);
}
return sqDiviations / m.getNumElements();
}
/** Rounds a double to the specified number of significant figures. */
public static double decimalRoundTo(double d, int significantFigures) {
double correctionTerm = Math.pow(10, significantFigures);
return Math.round(d * correctionTerm) / correctionTerm;
}
最佳答案
浮点运算是不精确的。当您将 n
个相同的 double
相加,并将结果除以 n
时,您并不总是得到开始时的数字。
例如,以下内容:
double x = 0.1;
double y = x + x + x;
System.out.println(y / 3. - x);
打印
1.3877787807814457E-17
我强烈推荐What Every Computer Scientist Should Know About Floating-Point Arithmetic .
关于java - Java中 double 的加法和除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15701626/