簡體   English   中英

c++ 中的比較近似

[英]Comparison approximation in c++

有沒有辦法按字典順序在std::vector<double>向量之間的比較中更改預定義<=<的精度?

我在代碼中的許多地方按字典順序比較std::vector<double>向量,第一個組件的比例(接近 0)與其他組件的比例(-700 和 700 之間)不同。 我希望精度為 1e-6,即對於兩個分量ab如果abs(ab)<=1e-6那么我們考慮a=b ,其中abdouble

由於我在代碼中的許多地方使用了<=< ,定義一個新的 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,但在我的情況下,第一個組件等於 (with epsilon=1e-6) 所以A>B

沒有什么好的方法可以改變算子的精度。

我建議您編寫自己的 function 迭代兩個向量並直接進行比較。 就像是:

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;
}

如果需要,您可以擴展它以處理不同大小的向量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM