[英]Comparison approximation in c++
有沒有辦法按字典順序在std::vector<double>
向量之間的比較中更改預定義<=
和<
的精度?
我在代碼中的許多地方按字典順序比較std::vector<double>
向量,第一個組件的比例(接近 0)與其他組件的比例(-700 和 700 之間)不同。 我希望精度為 1e-6,即對於兩個分量a
和b
如果abs(ab)<=1e-6
那么我們考慮a=b
,其中a
, b
是double
。
由於我在代碼中的許多地方使用了<=
和<
,定義一個新的 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.