比较浮点数和双精度值与增量? [英] Comparing float and double values with delta?

查看:95
本文介绍了比较浮点数和双精度值与增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,必须仔细比较浮点类型的值,以避免出现固有的浮点错误.可以通过将值与错误阈值进行比较来改善这一点.

As I understand the values of floating point types must be compared carefully to avoid issues with inherent floating point errors. This can be improved by comparing values with an error threshold.

例如,以下解决方案比简单的x == y测试更有用:

For example, the following solution is more usable than a straightforward x == y test:

static float CompareRelativeError(float x, float y) {
    return Math.Abs(x - y) / Math.Max(Math.Abs(x), Math.Abs(y));
}
static bool CompareAlmostEqual(float x, float y, float delta) {
    return x == y || CompareRelativeError(x, y) < delta;
}

// apologies if this is a poor example
if (CompareAlmostEqual(1f/10f, 0.1f)) { ... }

上述解决方案源自以下资源: 何时安全?直接在Java中比较2个float/double吗?

The above solution was derived from the following resource: Is it safe when compare 2 float/double directly in Java?

虽然我没有找到任何文献可以证实这一点,但对我来说,对于像x > y这样的比较,同样如此.例如,如果xy本质上相等,那么哪一个大于另一个...

Whilst I haven't been able to find any literature to confirm this, to me it seems that the same must hold true for comparisons like x > y. For example, if x and y are essentially equal, how can one be greater than the other...

static bool CompareGreater(float x, float y, float delta) {
    return x > y && !CompareAlmostEqual(x, y, delta);
}

因此,以下内容对x >= y有效:

And thus the following would be valid for x >= y:

static bool CompareGreaterOrEqual(float x, float y) {
    return x >= y;
}

我的假设正确吗?

推荐答案

平等测试正是将delta(或epsilon)技术用于浮点值的原因.

Equality testing is precisely the reason why the delta (or epsilon) technique is used for floating point values.

例如我们希望3等于2.999999 ...达到一定的精度.

e.g. we want 3 to be equal to 2.999999... to some precision.

因此,将CompareGreaterOrEqual方法定义为:

static bool CompareGreaterOrEqual(float x, float y) {
    return x >= y;
}

应该是:

static bool CompareGreaterOrEqual(float x, float y, float delta) {
    return x >= y || CompareAlmostEqual(x, y, delta);
}

注意:由于增量比较可确保相等性,因此第一个测试中的x >= y可能只是x > y:

Note: x >= y in first test could just be x > y since the delta comparison takes care of equality:

static bool CompareGreaterOrEqual(float x, float y, float delta) {
    return x > y || CompareAlmostEqual(x, y, delta);
}

这篇关于比较浮点数和双精度值与增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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