c++ - Magic number in boost::hash_combine -
the boost::hash_combine
template function takes reference hash (called seed
) , object v
. according docs, combines seed
hash of v
by
seed ^= hash_value(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
i can see deterministic. see why xor used.
i bet addition helps in mapping similar values apart probing hash tables won't break down, can explain magic constant is?
the magic number supposed 32 random bits, each equally 0 or 1, , no simple correlation between bits. common way find string of such bits use binary expansion of irrational number; in case, number reciprocal of golden ratio:
phi = (1 + sqrt(5)) / 2 2^32 / phi = 0x9e3779b9
so including number "randomly" changes each bit of seed; say, means consecutive values far apart. including shifted versions of old seed makes sure that, if hash_value()
has small range of values, differences spread across bits.
Comments
Post a Comment