python-3.x – numpy.bincount是否支持numpy.float128类型权重?

以下是使用numpy.bincount的示例代码

import numpy as np
a = np.array([1.0, 2.0, 3.0], dtype=np.float128)
b = np.array([1, 2, 0], dtype=np.int)
c = np.bincount(b, weights=a)

如果运行它,我会收到以下错误报告:

----> 1 c = np.bincount(b, weights=a)
TypeError: Cannot cast array data from dtype('float128') to dtype('float64') according to the rule 'safe'

这是np.bincount的错误吗?是否存在任何类似的功能,我可以用它来处理numpy.float128类型的权重?

最佳答案 我不一定称它为bug,但它不受支持. bincount()函数实现为
here.如您所见,权重参数直接转换为双数组:

if (!(wts = PyArray_ContiguousFromAny(weight, PyArray_DOUBLE, 1, 1))) {
    goto fail;
}

因此,无法将np.float128对象传递给bincount.

当然,如果不需要额外的精度,您可以按照注释中的建议将其强制转换为np.float64对象.

点赞