首頁 > 後端開發 > C++ > 主體

如何將'std::map”與浮點鍵一起使用:比較不準確的解決方案?

DDD
發布: 2024-11-14 22:15:03
原創
585 人瀏覽過

How to Use `std::map` with Floating-Point Keys: A Solution for Inaccurate Comparisons?

std::map Floating-Point Key Comparison

Using floating-point values as keys in std::maps can pose challenges due to the inherent imprecision of floating-point arithmetic. One common issue is that comparing floating-point keys using strict equality (==) may not always work as expected, as even seemingly exact values may not match due to precision error.

In the given code example, the loop attempts to find the key 3.0 in a std::map, but fails because the loop increments the search key using += 0.1, which may not precisely match the expected key value due to floating-point precision inaccuracies.

To address this issue, you could use the std::setprecision function in your program to specify the number of decimal places to consider when comparing keys. However, this approach can still be unreliable because it doesn't guarantee that the keys will compare exactly.

A better solution is to use an approximate comparison function in your std::map. You can define a custom comparator that uses an epsilon threshold to determine key equality. This allows you to compare keys within a certain tolerance, effectively ignoring minor precision differences:

struct fuzzy_double_comparator {
    bool operator() (const double a, const double b) const {
        return std::fabs(a - b) < epsilon;
    }
};
登入後複製

This comparator function can then be passed to the std::map constructor to use the approximate comparison:

std::map<double, double, fuzzy_double_comparator> mymap;
登入後複製

With this approach, you can find the key 3.0 in the std::map even if its actual value is slightly different due to floating-point precision limitations.

以上是如何將'std::map”與浮點鍵一起使用:比較不準確的解決方案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板