在标准集/映射中使用double作为键的方法 [英] Ways around using a double as a key in a std set/map

查看:100
本文介绍了在标准集/映射中使用double作为键的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在地图/集合中使用双精度键作为键的问题是浮点精度。

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

有人建议在您的比较函数中添加epsilon,但这意味着您的键将不再满足必要的严格弱排序标准。这意味着您将根据插入元素的顺序获得不同的集合/贴图。

Some people have suggested adding an epsilon in your compare function, but that means your keys will no longer fulfil the necessary strict weak ordering criterion. This means that you will get a different set/map depending on the order of inserting your elements.

如果您想基于双精度值来汇总/合并/合并数据,并愿意允许一定级别的舍入/ε(显然,

In the case where you want to aggregate/combine/merge data based on double values, and are willing to allow a certain level of rounding/epsilon (clearly, you'll have to), is the following solution a good idea?

将所有的双精度数(我们打算用作键)乘以精度因子(例如,将它们转换为整数)就可以了。 1e8)并四舍五入为最接近的整数(int)i + 0.5 (如果i> 0),然后创建一个设置/映射来禁用这些整数。提取键的最终值时,将整数除以精度系数即可得到双精度值(尽管四舍五入)。

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

推荐答案


将所有双打(我们打算用作键)转换为整数将它们乘以精度因子(例如1e8),并舍入到最接近的整数(int)i + 0.5 (如果i> 0),然后创建一个设置为提取这些键的最终值时,将整数除以精度系数即可得到双精度值(尽管四舍五入)。

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

我建议首先对地图使用整数类型的键(例如 long long ),并使用固定的修整符进行双重表示

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.

但这取决于您是否能够应用定点数学。如果您需要涵盖广泛的价值精度(例如+ -1e-7-+ -1e7),则这种方法将行不通。

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.

这篇关于在标准集/映射中使用double作为键的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆