NumPy 和 decimal128

NumPy and decimal128

假设我有一个包含 std::decimal::decimal128 (IEEE754R) 元素类型向量的内存缓冲区,我可以将其包装并公开为 NumPy 数组,并对这些十进制向量执行快速操作,例如计算向量的方差或自相关?我怎样才能做到最好?

Numpy 还不支持这种数据类型(至少在主流架构上是这样)。只有 float16、float32、float64 和非标准本机扩展双精度(通常为 with 80 bits) are supported. Put it shortly, only floating-point types natively supported by the target architecture. If the target machine support 128 bit double-precision numbers, then you could try the numpy.longdouble type but I do not expect this to be the case. In practice, x86 processors does not support that yet as well as ARM. IBM processors like POWER9 supports that natively but I am not sure they (fully) support the IEEE-754R standard. For more information please read this。请注意,理论上您可以将二进制数据包装在 Numpy 类型中,但您将无法(真正)用它做任何有用的事情。Numpy理论上可以使用新类型扩展代码,但请注意 Numpy 是用 C 而不是 C++ 编写的,因此在源代码中添加 std::decimal::decimal128 并不容易。

请注意,如果您真的想将此类类型包装在 Numpy 数组中而不必 change/rebuild Numpy 代码,可以将您的类型包装在 pure-Python class 中。但是,请注意性能会很差,因为使用 pure-Python 对象会阻止在 Numpy 中完成的所有优化(例如 SIMD 向量化、使用快速本机代码、针对给定类型优化的特定算法等)。