Home > Backend Development > C++ > body text

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

DDD
Release: 2024-11-14 22:15:03
Original
584 people have browsed it

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;
    }
};
Copy after login

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;
Copy after login

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.

The above is the detailed content of How to Use `std::map` with Floating-Point Keys: A Solution for Inaccurate Comparisons?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template