Skip to content

Commit 19f2e47

Browse files
committed
py: Add very simple but correct hashing for float and complex numbers.
Hashing of float and complex numbers that are exact (real) integers should return the same integer hash value as hashing the corresponding integer value. Eg hash(1), hash(1.0) and hash(1+0j) should all be the same (this is how Python is specified: if x==y then hash(x)==hash(y)). This patch implements the simplest way of doing float/complex hashing by just converting the value to int and returning that value.
1 parent bb29648 commit 19f2e47

3 files changed

Lines changed: 3 additions & 0 deletions

File tree

py/obj.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,7 @@ void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t s
718718

719719
#if MICROPY_PY_BUILTINS_FLOAT
720720
// float
721+
static inline mp_int_t mp_float_hash(mp_float_t val) { return (mp_int_t)val; }
721722
mp_obj_t mp_obj_float_binary_op(mp_uint_t op, mp_float_t lhs_val, mp_obj_t rhs); // can return MP_OBJ_NULL if op not supported
722723

723724
// complex

py/objcomplex.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ STATIC mp_obj_t complex_unary_op(mp_uint_t op, mp_obj_t o_in) {
117117
mp_obj_complex_t *o = MP_OBJ_TO_PTR(o_in);
118118
switch (op) {
119119
case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->real != 0 || o->imag != 0);
120+
case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(o->real) ^ mp_float_hash(o->imag));
120121
case MP_UNARY_OP_POSITIVE: return o_in;
121122
case MP_UNARY_OP_NEGATIVE: return mp_obj_new_complex(-o->real, -o->imag);
122123
default: return MP_OBJ_NULL; // op not supported

py/objfloat.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ STATIC mp_obj_t float_unary_op(mp_uint_t op, mp_obj_t o_in) {
106106
mp_float_t val = mp_obj_float_get(o_in);
107107
switch (op) {
108108
case MP_UNARY_OP_BOOL: return mp_obj_new_bool(val != 0);
109+
case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(val));
109110
case MP_UNARY_OP_POSITIVE: return o_in;
110111
case MP_UNARY_OP_NEGATIVE: return mp_obj_new_float(-val);
111112
default: return MP_OBJ_NULL; // op not supported

0 commit comments

Comments
 (0)