python中如何定义float_如何定义自定义float类型numpy dtypes(C-API)

1586010002-jmsa.png

I have a custom float data type that emulates 128bit floats using two 64bit floats (the double-double class dd_real from the QD library). From C++ I want to export an ndarray to python. I already know how to do this for 64bit floats, but for double-doubles I somehow need to specify my own custom dtype. How to do that?

Note: numpy has its own 128bit float (np.float128) unfortunately this maps to long double in C/C++ which is merely an 80bit-float stored in 128bit (on all of my platforms).

In fact, one should be able to do this exactly in the same way that numpy exports np.float128 (I just don't know how that is done), with the only difference that it uses dd_real on the C++ side instead of long double.

If this helps, I already exported the C++ type dd_real to python using boost::python maybe this can be reused somehow.

So far I was able to research the following

The numpy documentation for dtypes refers to C-API for how to export custom dtypes, but that document somehow only explains the existing dtypes not how to create new ones.

When browsing stackoverflow I found this example, but I wonder if for dd_real this could be simpler. I also don't see where the dtype is actually generated. Maybe only in python __ init__ via np.typeDict['quaternion'] = np.dtype(quaternion). How to use that dtype in C++ when I want to generate an ndarray?

解决方案

The repository you linked to,

https://github.com/numpy/numpy-dtypes

probably contains the simplest possible examples on how to add new dtype to Numpy. I'm not aware of an easier way. Note the calls to register_cast_function and REGISTER_UFUNC in these files: these tell Numpy how operations such as multiplication and casting should be dealt with on an element-by-element level.

However, if what you actually want to do is to only export your data, you could just export as an array of doubles, or maybe bundling two doubles to a single data type

np.dtype([('a', double), ('b', double)])

Then, you'd need to write separate functions to do operations on these arrays (as arr1 * arr2 won't do what you want here). One possible way to go further and make also arr1 * arr2 to work would be to subclass np.ndarray your data type, overriding __mul__ etc operations.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值