为什么是python;dtype=float";8字节而不是4字节?
这些天,我已经从Matlab切换到NumPy/SciPy 今天,当我试图加载以“二进制格式”存储的数据时,遇到了一个奇怪的问题。音频数据以4字节单精度浮点数格式存储。我先尝试了以下方法为什么是python;dtype=float";8字节而不是4字节?,python,numpy,binary,floating-point,Python,Numpy,Binary,Floating Point,这些天,我已经从Matlab切换到NumPy/SciPy 今天,当我试图加载以“二进制格式”存储的数据时,遇到了一个奇怪的问题。音频数据以4字节单精度浮点数格式存储。我先尝试了以下方法 data = np.fromfile('out.raw', dtype=float) # This is wrong plt.plot(data) 但它不起作用。经过一番搜索,我尝试了以下方法,效果如预期: data = np.fromfile('out.raw', dtype=np.float32) # Th
data = np.fromfile('out.raw', dtype=float) # This is wrong
plt.plot(data)
但它不起作用。经过一番搜索,我尝试了以下方法,效果如预期:
data = np.fromfile('out.raw', dtype=np.float32) # This is okay.
plt.plot(data)
根据我以前使用C/C++的经验,我希望“float”是一种4字节单精度浮点类型。但事实证明浮点是8字节的数据,在上面的例子中,我应该使用np.float32
关于这一点,我有两个问题
Q1为什么浮点是8字节而不是4字节,这可能会让C/C++程序员感到困惑?
Q2为什么不能使用dtype=float32。这给我带来了一个错误。我似乎应该使用dtype=np.float32?
谢谢大家! 这是因为
float
是一种本机Python数据类型,它有一个底层的C-double。这来自Python核心,而不是numpy或scipy
这些类型更具体,更符合您的期望:
bool_ Boolean (True or False) stored as a byte
int_ Default integer type (same as C long; normally either int64 or int32)
intc Identical to C int (normally int32 or int64)
intp Integer used for indexing (same as C ssize_t; normally either int32 or int64)
int8 Byte (-128 to 127)
int16 Integer (-32768 to 32767)
int32 Integer (-2147483648 to 2147483647)
int64 Integer (-9223372036854775808 to 9223372036854775807)
uint8 Unsigned integer (0 to 255)
uint16 Unsigned integer (0 to 65535)
uint32 Unsigned integer (0 to 4294967295)
uint64 Unsigned integer (0 to 18446744073709551615)
float_ Shorthand for float64.
float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
float64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
complex_ Shorthand for complex128.
complex64 Complex number, represented by two 32-bit floats (real and imaginary components)
complex128 Complex number, represented by two 64-bit floats (real and imaginary components)
如果您的问题是,当底层C-type为double
时,为什么核心Python使用术语float
,答案是Python试图成为比C这样的低级语言更高级别的抽象。术语float
表示浮点数的概念,而不是指定大小的特定C类型,如float
或double
相反,numpy允许较低级别的精确大小和内存布局控制。这是其优化的关键。然而,这些优化和控制细节的能力是以将代码从“您正在尝试做什么”的高级抽象转移到“指定如何做的细节”的世界为代价的