java - Java中 double 的加法和除法

标签 java double division ejml

我在我的项目中使用 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/

相关文章:

c - c 中的除法没有给出预期值

java - 类对象定义排序行为

java - 在 Spring Boot 应用程序中对 @Value 注释字段实现约束

java - Firebase 退出 Google

Java 程序将判断用户输入是否为 double

html - 网页抓取:网页抓取的对象与网站上的信息不匹配并导致 RStudio 崩溃

java - 在java中执行另一个jar中的一个jar

Java实现接口(interface)Comparable,将手动输入的数据与生成的数据进行比较

java - 为什么不能将 Byte 对象/字节值转换为 Double 对象?从 Byte 到 Double 的转换会影响精度吗?

PHP 除法返回不同的结果 (Linux/Windows)