Because computers can't accurately store floating-point values as you know, you should try to avoid equality comparison between them or use some approach like "relative error" as mentioned in this resource.
I have a table of data where keys and mapped values are both floats. Although I can provide my own Compare logic using the above "relative error", this Compare template parameter is only used for "strict weak ordering". In other words, it only tells whether two floating keys in my case have a "less than" (<) ordering so that the Map can order keys in acceding order.
For example if Compare says the predicate of "float1 < float2" is false, it either means float1 = float2 or float1 > float2.
But the C++ Map doesn't allow you to customize either an equal or a greater than logic. This is especially troubling when you want to use Map's find() method based on floating-point values. In this case, the Map will use the computer's intrinsic equal(=) comparison logic, which is not reliable for floating-point value' comparison as you know.
Fortunately in my case I know the maximal precision and scale for all my floating keys. So I first safely mapped my floating key to integers and then saved the corresponding integer keys into the map.
No comments:
Post a Comment