Ways around using a double as a key in a std set/map

后端 未结 2 1265
春和景丽
春和景丽 2021-02-08 03:54

The problem of using doubles as keys in maps/sets is floating point precision.

Some people have suggested adding an epsilon in your compare function, but that means you

2条回答
  •  悲哀的现实
    2021-02-08 04:36

    Convert all the doubles (where we intended as keys) into integers by multiplying them by the precision factor (e.g. 1e8) and rounding to the nearest integer (int)i+0.5(if i>0), then create a set/map that keys off these integers. When extracting the final values of the keys, divide the ints by the precision factor to get the double value back (albeit rounded).

    Instead of dividing by the precision factor to get the doubles back, simply store the double together with the associated value in a struct, and put that struct in the dictionary as the "value" for that integer key. That way, the original double value is still around and can be used for calculations. Just not for the key search.

    If, however, you can live with slightly rounded values (due to the fact you simply divide an integer by an epsilon), your suggested approach is already good enough.

    As the other answer says, it very much depends on the range of the values. If some are extremely huge and others are extremely small, then your approach to get integer keys won't work. If they are only a few digits apart, then it might.

提交回复
热议问题