python - numpy:从复杂数据类型中确定相应的 float 数据类型

标签 python numpy numpy-ndarray numpy-dtype

我正在使用两个 numpy float 数组

Rs = np.linspace(*realBounds, realResolution, dtype=fdtype)
Is = np.linspace(*imagBounds, imagResolution, dtype=fdtype)

用形状 (realResolution, imagResolution) 制作复数网格 Zs。我只想指定 Zs 的数据类型,并用它来确定 float 据类型 fdtype

据我了解this page ,复杂数据类型总是表示为具有相同数据类型的两个 float ,因此 RsIs 都有 dtype=fdtype。如果 Zs 的数据类型指定为 np.csingle 那么我希望 fdtypenp.single ,如果指定为 np.dtype("complex128") 那么我希望 fdtypenp.dtype("float64") , 等等。有什么好的方法可以做到这一点吗?

编辑:我对反函数同样感兴趣,例如将 np.single 发送到 np.csingle

最佳答案

我不认为 numpy 中有这样的函数,但您可以使用 num 轻松实现自己的功能,它唯一标识每个内置类型:

def get_corresonding_dtype(dt):
    return {11: np.csingle,
            12: np.cdouble,
            13: np.clongdouble,
            14: np.single,
            15: np.double,
            16: np.longdouble}[np.dtype(dt).num]

字典是从{np.dtype(dt).num: dt for dt in (np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble) 返回

{11: numpy.float32,
 12: numpy.float64,
 13: numpy.longdouble,
 14: numpy.complex64,
 15: numpy.complex128,
 16: numpy.clongdouble}

win-amd64 (sysconfig.get_platform())。名称可能会有所不同,例如在 linux-x86_64 上,它显示 numpy.complex256 而不是 numpy.clongdouble,但是感谢 num,你不需要不需要特别注意。

例如对于所有的np.double, np.float_, np.float64, float , 'float64' 等,get_corresonding_dtype 将返回 numpy.complex128

如果您愿意,还可以将 np.half as 23: np.csingle 添加到字典中,因为 numpy 中没有复杂的 half/float16 类型。

关于python - numpy:从复杂数据类型中确定相应的 float 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72692790/

相关文章:

arrays - Mpi4Py - 发送无副本的 numpy 子数组(非连续内存)

python-3.x - [::-1] 在 numpy 中实际上做了什么?

python - 为 NN 混洗两个 numpy 数组

python - 在没有循环的情况下将 numpy 数组中的 1's to 0 and 0' s 更改为 1

c# - 从 Python 调用 C# 中的特定属性重载

python - Unetstack - Python API - 组合 Tx/Rx

python - 根据数据帧 B 中其他两列给出的范围填充数据帧 A 中的列

python - 稀疏矩阵上 hstack 的类型错误

python - 从 numpy 数组中删除一个元素

python - numpy 数组大小的困惑