Hen*_*ski 3 python arrays floating-point numpy python-2.7
我有一个由 NumPy 创建的二进制矩阵。该矩阵有 5 行和 32 列。
array([[1, 1, ..., 1, 1],
[0, 1, ..., 0, 1],
[1, 1, ..., 0, 1],
[0, 0, ..., 1, 0],
[1, 1, ..., 0, 1]])
Run Code Online (Sandbox Code Playgroud)
我将矩阵行转换为字符串,然后放在整数旁边。
str = ''.join(map(str,array[0])).replace(' ','')
int(str, base=2)
Run Code Online (Sandbox Code Playgroud)
如何将字符串转换为浮点数(float32 - IEEE-754 single)?
>>> a = [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0,
... 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1]
>>> i = int(''.join(map(str, a)), 2)
>>> import struct
>>> struct.unpack('f', struct.pack('I', i))[0]
1.100000023841858
Run Code Online (Sandbox Code Playgroud)
import struct
matrix = array(...)
st_i = struct.Struct('I')
st_f = struct.Struct('f')
float_values = [
st_f.unpack(st_i.pack(int(''.join(map(str, a)), 2)))
for a in matrix
]
Run Code Online (Sandbox Code Playgroud)
注意:根据数组的字节顺序,需要在结构体格式前添加<
, 。>
顺便说一句,覆盖str
不是一个好主意。str
赋值后不能使用函数/类型。