A way to hashing floating-point in Lua 5.4
Last updated on 8 minutes ago
Hash for Float
This function is going to create a integer hash value for
floating-point input, and this artical is about to dive into the
details. The calculation of hash for floating-point conceptlly is pretty
intuitive. The core expression is
n = frexp(n, &i); return (n * INT_MAX) + i;
But, there
are several subtleties to be considered...
Main function defines here:
1 |
|
Some auxiliary function defines here:
1 |
|
There are several key points to be considered:
- How to check if a floating-point number is inf/-inf/nan:
1 |
|
- Implication of lua_numbertointeger
The main role of this function is checking if a integer number within
the range of integer(which is long long
) and converting it
to integer. Take an example of long long
for integer,
LLONG_MAX
can not be exactly represented by
double but LLONG_MIN
does. Besides, the absolute
value of LLONG_MIN
is one greater than
LLONG_MAX
. Therefore, if we want to check if a integer(say
num
) to be converted within the range of
long long
, we can manually check it by
num >= double(LLONG_MIN) && num < double(-LLONG_MIN)
.
- Implication of
cast_int(u <= cast_uint(INT_MAX) ? u : ~u)
Firstly, u
is unsigned int
, which is always
greater than and equal to zero. By contrast, int
has
negative value. Secondly, if u
is nun-negative value, we
just return it. If u
is negative value, we cannot directly
return -u
, since
abs(INT_MIN) = abs(INT_MAX) + 1
, it will cause overflow.
Therefore, we just flip all bits for u
but not adding
one(negative a negative value is equvalent to fliping all bits and
adding one).