Rares said:
Hello,
How does find works for a map where the key is float?
I know you cannot just simply compare floats for equality,
Well, you can. It just so happens that it is _often_ not what you want to
do.
you need to use fabs and some epsilon.
Sometimes, that is what you want to do.
I know map does not use equality, but uses "less". Still two floats
(float a,b
might show as a > b when in fact they are equal.
Well, there are cases where one can get that impression. The standard allows
floating point numbers to have excess precision during computations.
However, operator< has a perfectly well-defined and natural meaning for
float objects (i.e., the corresponding regions in memory). If you make sure
that the floats that you compute are written to memory, they will compare
equal if and only if they are equal and operator< will do what you expect.
The trick part is making sure that the objects are written to memory.
Now, with regard to find(), one may hope that the keys are already written
to memory (if not, declaring the map object volatile or declaring the map
as map< volatile float, ...> might do the trick). Still, we have to worry
about the parameter. I have recently learned on this list that it is enough
that the parameter is passed by value. The compiler is then required to
initialize the corresponding local object accordingly (though, I also
learned that many compilers get this wrong). Unfortunately, map::find()
takes the parameter as a const reference. What you could do is something
like this:
float rid_excess_precision ( float x ) {
return ( x );
}
and then call
my_map.find( rid_excess_precision( float x ) )
An orthogonal issue (and probably a more serious one) is how you obtain the
keys for which you want to search in the first place. Even if you get
around all the problems above, you will only find the entry in the map if
they match the stored values _exactly_ (and that is what a map is supposed
to do). With floats, it can be very tricky to compute the same value twice.
If you can guarantee precision of your computations only up to a certain
epsilon, then you might be better off using map< long, ... > where you use
floor( x / epsilon )
as the key. (You could also come up with different schemes that do a more
logarithmic mapping if you need a better resolution near 0).
Best
Kai-Uwe Bux