我正在使用两个 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 ,因此 Rs
和 Is
都有 dtype=fdtype
。如果 Zs
的数据类型指定为 np.csingle
那么我希望 fdtype
为 np.single
,如果指定为 np.dtype("complex128")
那么我希望 fdtype
为 np.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/