KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
The following code is supposed to find the key 3.0 in a std::map which exists. But due to floating point precision it won't be found. map<double, double> mymap; mymap[3.0] = 1.0; double t = 0.0; for(int i = 0; i < 31; i++) { t += 0.1; bool contains = (mymap.count(t) > 0); } In the above example, contains will always be false . My current workaround is just multiply t by 0.1 instead of adding 0.1, like this: for(int i = 0; i < 31; i++) { t = 0.1 * i; bool contains = (mymap.count(t) > 0); } Now the question: Is there a way to introduce a fuzzyCompare to the std::map if I use double keys? The common solution for floating point number comparison is usually something like a-b < epsilon . But I don't see a straightforward way to do this with std::map . Do I really have to encapsulate the double type in a class and overwrite operator<(...) to implement this functionality?
Tags (comma-separated)
Save Edits
Cancel