One of my coworkers recently brought up an interesting trick to reliably use floating point numbers as keys in something like a std::map
in C++.
Assumi
First, you shouldn't divide by ticksize
, you should multiply by the inverse of ticksize
, which likely would be exactly representable as double
considering the application you describe. This inverse would be 20.0
in your example.
Second, you can make the transformation slightly simpler and in my opinion more readable thus:
after multiplying price
by the inverse of ticksize
, round from double to the nearest integer, either as a long long
(function llround
) or as a double
(function nearbyint
). There is no inherent reason why you shouldn't use double
as the key of std::map
, as long as you use compatible hash and equality functions (the hash function should return the same hash for +0. and -0. if the equality is ==
, and probably you shouldn't use NaN as key if you are using ==
as equality).
In code:
priceKey = llround(price * inverseticksize);