【问题标题】:Why is the python "dtype=float" 8-byte rather than 4-byte?为什么 python "dtype=float" 是 8 字节而不是 4 字节?
【发布时间】:2023-03-28 22:47:01
【问题描述】:

这些天,我已经从 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) # This is okay.
plt.plot(data)

根据我之前使用 C/C++ 的经验,我曾预计“float”是 4 字节单精度浮点类型。但事实证明,float 是 8 字节数据,在上述情况下,我应该使用 np.float32。

对此我有两个问题。

第一季度为什么浮点数是 8 字节而不是 4 字节,这可能会让 C/C++ 程序员感到困惑?

第二季度为什么我不能使用 dtype=float32。这会给我带来一个错误。我似乎应该使用 dtype=np.float32?

谢谢!

【问题讨论】:

    标签: python numpy binary floating-point


    【解决方案1】:

    这是因为 float 是一种原生 Python 数据类型,它具有底层 C-double。这是来自 Python 核心,而不是来自 numpyscipy

    numpy and 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)
    

    如果您的问题是为什么核心 Python 在底层 C 类型为 double 时使用术语 float,答案是 Python 试图成为比 C 等低级语言更高级别的抽象。术语float 表示浮点数的概念,而不是指定大小的特定C 类型,例如floatdouble

    相比之下,numpy 允许对确切大小和内存布局进行较低级别的控制。这是其优化的关键。然而,这些优化和控制细节的能力是以将代码从“你正在尝试做什么”的高级抽象转移到“指定如何完成的细节”的世界为代价的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-13
      • 2014-09-24
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 2021-05-25
      相关资源
      最近更新 更多