执行双值相等比较时,epsilon值应该是多少 [英] What should be the epsilon value when performing double value equal comparison

查看:163
本文介绍了执行双值相等比较时,epsilon值应该是多少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是该程序的输出。

value is : 2.7755575615628914E-17
Double.compare with zero : 1
isEqual with zero : true

我的问题是,什么应该是epsilon值?有没有强大的方法来获取价值,而不是从天空中挑选一个数字。

package sandbox;

/**
 *
 * @author yccheok
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        double zero = 1.0/5.0 + 1.0/5.0 - 1.0/10.0 - 1.0/10.0 - 1.0/10.0 - 1.0/10.0;
        System.out.println("value is : " + zero);
        System.out.println("Double.compare with zero : " + Double.compare(zero, 0.0));
        System.out.println("isEqual with zero : " + isEqual(zero, 0.0));
    }

    public static boolean isEqual(double d0, double d1) {
        final double epsilon = 0.0000001;
        return d0 == d1 ? true : Math.abs(d0 - d1) < epsilon;
    }
}


推荐答案

回答你的第二个问题是否定的。有限机器精度误差的大小可以任意大:

The answer to your second question is no. The magnitude of finite-machine precision error can be arbitrarily large:

public static void main(String[] args) {
    double z = 0.0;
    double x = 0.23;
    double y = 1.0 / x;
    int N = 50000;
    for (int i = 0; i < N; i++) {
        z += x * y - 1.0;
    }
    System.out.println("z should be zero, is " + z);
}

这给出 ~5.55E-12 ,但是如果你增加 N ,你可以得到你想要的任何级别的错误。

This gives ~5.55E-12, but if you increase N you can get just about any level of error you desire.

关于如何编写数值稳定的算法,有大量过去和现在的研究。这是一个难题。

There is a vast amount of past and current research on how to write numerically stable algorithms. It is a hard problem.

这篇关于执行双值相等比较时,epsilon值应该是多少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆