Comparison approximation in c++

231 views Asked by At

Is there a way to change the precision of the predefined <= and < in the comparison between std::vector<double> vectors lexicographically ?

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). I want the precision to be 1e-6, i.e for two components a and b if abs(a-b)<=1e-6 then we consider a=b, where a, b are double.

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.

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.

1

There are 1 answers

0
Dean Johnson On

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. 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 false; // The vectors are "equal"
}

You can expand this to handle vectors of different sizes if needed.