I want to use Double
(or Float
) as keys in a Hashmap
Map<Double, String> map = new HashMap<Double, String>()
map.put(1.0, "one");
System.out.println(map.containsKey(Math.tan(Math.PI / 4)));
and this returns false.
if I were comparing these two numbers I would have done something like this
final double EPSILON = 1e-6;
Math.abs(1.0 - Math.tan(Math.PI / 4)) < EPSILON
But since Hashmap
would use hashcode
it breaks things for me.
I thought to implement a roundKey
function that rounds to some multiple of EPSILON
before using it as a key
map.put(roundKey(1.0), "one")
map.containsKey(roundKey(Math.tan(Math.PI / 4)))
- is there a better way ?
- what is the right way to implement this
roundKey