检查带有公差的值 [英] Check values with tolerance

查看:111
本文介绍了检查带有公差的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查一个值是否等于+或 - 2另一个值。

I am trying to check whether one value equals + or - 2 the other value.

这就是我遇到的情况。

    for (int lineNumber : errorLineList) {
        if (lineNumber == startLineNumber
                || lineNumber == (startLineNumber + 1)
                || lineNumber == (startLineNumber + 2)
                || lineNumber == (startLineNumber - 1)
                || lineNumber == (startLineNumber - 2)) {
            lineFound = true;
            break;
        }
    }

但是如果我希望公差为5,然后我必须添加10个支票。

But here if i want the tolerance to be 5, then i have to add 10 checks.

在java中还有其他优雅的方法吗。

Is there any other elegant way to do this in java.

推荐答案

这在使用双打时经常需要,因为你可以得到小的舍入错误。

This is often need when using doubles as you can get small rounding errors.

if(Math.abs(lineNumber - startLineNumber) <= 2)

您可以将2更改为5。这是说;如果两个值之间的差值小于2.即它可能是-2,-1,0,1或2.

You can change 2 to 5. This is says; if the difference between two values is less than 2. i.e it could be -2, -1, 0, 1 or 2.

对于 double 类似的解决方案是使用

For double a similar solution is to test "equality" using

if(Math.abs(a - b) < ERR) // where ERR is 1e-4 or 1e-9

什么是好的要使用的ERR值取决于具体情况。

What is a good value of ERR to use depends on the situation.

这篇关于检查带有公差的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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