Skip to content

Commit 8eece3e

Browse files
committed
hash function for complex
1 parent 8345684 commit 8eece3e

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

pandas/_libs/src/klib/khash_python.h

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,11 +255,26 @@ Py_hash_t PANDAS_INLINE _Pandas_HashDouble(double val){
255255
}
256256

257257

258-
Py_hash_t PANDAS_INLINE hash_float(PyFloatObject* key){
258+
Py_hash_t PANDAS_INLINE floatobject_hash(PyFloatObject* key){
259259
return _Pandas_HashDouble(PyFloat_AS_DOUBLE(key));
260260
}
261261

262262

263+
// replaces _Py_HashDouble with _Pandas_HashDouble
264+
Py_hash_t PANDAS_INLINE complexobject_hash(PyComplexObject* key){
265+
Py_uhash_t realhash = (Py_uhash_t)_Pandas_HashDouble(key->cval.real);
266+
Py_uhash_t imaghash = (Py_uhash_t)_Pandas_HashDouble(key->cval.imag);
267+
if (realhash == (Py_uhash_t)-1 || imaghash == (Py_uhash_t)-1) {
268+
return -1;
269+
}
270+
Py_uhash_t combined = realhash + _PyHASH_IMAG * imaghash;
271+
if (combined == (Py_uhash_t)-1) {
272+
return -2;
273+
}
274+
return (Py_hash_t)combined;
275+
}
276+
277+
263278
khint32_t PANDAS_INLINE kh_python_hash_func(PyObject* key){
264279
Py_hash_t hash;
265280
// For PyObject_Hash holds:
@@ -270,7 +285,13 @@ khint32_t PANDAS_INLINE kh_python_hash_func(PyObject* key){
270285
// we cannot use kh_float64_hash_func
271286
// becase float(k) == k holds for any int-object k
272287
// and kh_float64_hash_func doesn't respect it
273-
hash = hash_float((PyFloatObject*)key);
288+
hash = floatobject_hash((PyFloatObject*)key);
289+
}
290+
else if (PyComplex_CheckExact(key)) {
291+
// we cannot use kh_complex128_hash_func
292+
// becase complex(k,0) == k holds for any int-object k
293+
// and kh_complex128_hash_func doesn't respect it
294+
hash = complexobject_hash((PyComplexObject*)key);
274295
}
275296
else {
276297
hash = PyObject_Hash(key);

0 commit comments

Comments
 (0)