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

后端 未结 2 1367
春和景丽
春和景丽 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:39

    "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)."

    I would recommend using integer type keys (e.g. long long) for the map in first place, and trim them for double representation using a fixed precision for division.

    But that depends, if you are able to apply fix point math for your actual use case. If you need to cover a wide range of value precisions (like e.g. +-1e-7 - +-1e7), such approach won't work.

提交回复
热议问题