Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Decimal type as keys in a Dictionary?

I'm about to create a dictionary where each value has a numeric key, obtained by an experimental calculation.

I know that double and any other floating-point type is not well suited to be used as a key, since it's hard to compare two floating-point numbers regarding uniqueness or equality.

Does anyone knows if Decimal is a good candidate with this respect? The alternative would be to convert the double to string with a given precision, but that sounds to me like an inelegant workaround.

like image 201
heltonbiker Avatar asked Feb 04 '13 18:02

heltonbiker


People also ask

What data types can be used as key for dictionary?

For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. Values, on the other hand, can be any type and can be used more than once.

Can dict keys be numbers?

Yes. "...can be any immutable type; strings and numbers can always be keys..." Literally from the link you posted: "Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys."

Do dictionary keys need to be strings?

The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.


1 Answers

There is not much difference between using float or decimal as key in dictionary. Both represent number with exponent - so both suffer from the same comparison issue just in different scale.

Either would be ok for Dictionary if you need bit-wise equality, if you need to keys for "about the same value" you need to make it custom key which would round values in some known way to put similar results in the same bucket...

like image 89
Alexei Levenkov Avatar answered Nov 06 '22 05:11

Alexei Levenkov