Skip to content

Commit fdbfdec

Browse files
committed
hash function for complex
1 parent 1c10229 commit fdbfdec

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

pandas/_libs/src/klib/khash_python.h

+23-2
Original file line numberDiff line numberDiff line change
@@ -264,11 +264,26 @@ Py_hash_t PANDAS_INLINE _Pandas_HashDouble(double val){
264264
}
265265

266266

267-
Py_hash_t PANDAS_INLINE hash_float(PyFloatObject* key){
267+
Py_hash_t PANDAS_INLINE floatobject_hash(PyFloatObject* key){
268268
return _Pandas_HashDouble(PyFloat_AS_DOUBLE(key));
269269
}
270270

271271

272+
// replaces _Py_HashDouble with _Pandas_HashDouble
273+
Py_hash_t PANDAS_INLINE complexobject_hash(PyComplexObject* key){
274+
Py_uhash_t realhash = (Py_uhash_t)_Pandas_HashDouble(key->cval.real);
275+
Py_uhash_t imaghash = (Py_uhash_t)_Pandas_HashDouble(key->cval.imag);
276+
if (realhash == (Py_uhash_t)-1 || imaghash == (Py_uhash_t)-1) {
277+
return -1;
278+
}
279+
Py_uhash_t combined = realhash + _PyHASH_IMAG * imaghash;
280+
if (combined == (Py_uhash_t)-1) {
281+
return -2;
282+
}
283+
return (Py_hash_t)combined;
284+
}
285+
286+
272287
khint32_t PANDAS_INLINE kh_python_hash_func(PyObject* key){
273288
Py_hash_t hash;
274289
// For PyObject_Hash holds:
@@ -279,7 +294,13 @@ khint32_t PANDAS_INLINE kh_python_hash_func(PyObject* key){
279294
// we cannot use kh_float64_hash_func
280295
// becase float(k) == k holds for any int-object k
281296
// and kh_float64_hash_func doesn't respect it
282-
hash = hash_float((PyFloatObject*)key);
297+
hash = floatobject_hash((PyFloatObject*)key);
298+
}
299+
else if (PyComplex_CheckExact(key)) {
300+
// we cannot use kh_complex128_hash_func
301+
// becase complex(k,0) == k holds for any int-object k
302+
// and kh_complex128_hash_func doesn't respect it
303+
hash = complexobject_hash((PyComplexObject*)key);
283304
}
284305
else {
285306
hash = PyObject_Hash(key);

0 commit comments

Comments
 (0)