简体   繁体   English

c++ 中的比较近似

[英]Comparison approximation in c++

Is there a way to change the precision of the predefined <= and < in the comparison between std::vector<double> vectors lexicographically?有没有办法按字典顺序在std::vector<double>向量之间的比较中更改预定义<=<的精度?

I am comparing between std::vector<double> vectors lexicographically in many places in my code, the scale of the first component (close to 0) is different from the scale of the other components (between -700 and 700).我在代码中的许多地方按字典顺序比较std::vector<double>向量,第一个组件的比例(接近 0)与其他组件的比例(-700 和 700 之间)不同。 I want the precision to be 1e-6, ie for two components a and b if abs(ab)<=1e-6 then we consider a=b , where a , b are double .我希望精度为 1e-6,即对于两个分量ab如果abs(ab)<=1e-6那么我们考虑a=b ,其中abdouble

Since I used <= and < in many places in the code, defining a new function that replaces <= and < to compare between vectors is risky (I make skip some vectors), so I am wondering if it is possible to change the precision of <= and < so this change will apply to all the comparisons directly.由于我在代码中的许多地方使用了<=< ,定义一个新的 function 替换<=<来比较向量是有风险的(我跳过了一些向量),所以我想知道是否可以改变精度<=<因此此更改将直接应用于所有比较。

An example of vectors I have: A=(-2.6666666666666936, 33497.435897435964, -300.51282051282101) , B=(-2.6666666666666914, 17403.589743589808, -251.28205128205173) , the result by using <= , is that A<=B because of the first component, but in my case, the first components are equal with (with epsilon=1e-6) so A>B . An example of vectors I have: A=(-2.6666666666666936, 33497.435897435964, -300.51282051282101) , B=(-2.6666666666666914, 17403.589743589808, -251.28205128205173) , the result by using <= , is that A<=B because of the first component,但在我的情况下,第一个组件等于 (with epsilon=1e-6) 所以A>B

There is no good way to change the precision of the operators.没有什么好的方法可以改变算子的精度。

I'd suggest you write your own function that iterates over the two vectors and does the comparisons directly.我建议您编写自己的 function 迭代两个向量并直接进行比较。 Something like:就像是:

bool approxLessThan(
        const std::vector<double>& a,
        const std::vector<double>& b,
        double tolerance) {
    // feel free to handle this differently
    assert(a.size() == b.size());

    for (size_t i =0; i < a.size(); i++) {
        double dif = a[i] - b[i];
        if (std::abs(dif) > tolerance)
            return dif < 0.0; // change this to <= as needed
    }
    return true;
}

You can expand this to handle vectors of different sizes if needed.如果需要,您可以扩展它以处理不同大小的向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM