我在我的项目中使用 EJML 库。我编写了一个计算 SimpleMatrix 行向量方差的方法。在某些时候,我注意到在将等元素向量传递给此方法时,我得到了一个 > 0.0 的方差。
我写这篇文章是为了进一步调查,并惊讶地发现最后一行打印错误,尽管之前的打印没有产生任何输出。
// 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());
有人可以解释为什么等元素向量的平均值大于其元素之一吗?
跟进:解决了我的问题:
/**
* 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;
}