Is there a way to get a hashcode of a float with epsilon?

前端 未结 5 1844
梦如初夏
梦如初夏 2021-01-04 07:46

It is well known that comparing floats by == is usually a mistake. In a 3D-vector class (with float components X, Y, Z) i wrote, two vectors are considered equa

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 08:29

    It's impossible assuming you want to have the normal hashcode/equality properties:

    • If X = Y and Y = Z then X = Z (transitivity)
    • If X = Y then Y = X (commutivity)
    • X = X for all X (reflexivity)

    The first rule is the problem - because if each value is deemed "equal" to the next greater representable number, you end up with all numbers being equal. For instance, suppose a number is deemed equal to another they're within 0.1:

    0 equals 0.08 0.08 equals 0.16 0.16 equals 0.24

    => 0 equals 0.16 by the transitivity rule => 0 equals 0.24 by the transitivity rule

    (etc)

    If you ignore the transitivity rule, then you still (presumably) want "equal" values to have equal hashcodes. This effectively enforces the transitivity rule - in the above example, 0 and 0.08 have to have equal hashcodes, as do 0 and 0.16. Therefore 0 and 0.16 have to have equal hashcodes, and so on. Therefore you can have no useful hashcode - it has to be a constant.

提交回复
热议问题