numpy float16数据转换之精度损失

本文探讨了32位浮点数与16位浮点数之间的相互转换过程及其对数值精度的影响。通过Python示例代码展示,在进行类型转换时,虽然二进制表示中部分位会被截断为0,但十进制表示形式可能会变得更长。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When you convert from 32bit float to 16bit float and back, some of the bits are lost, but note that this does not mean the decimal representation will be shorter. When you print out a floating point number, the computer only prints the closest decimal representation of the binary value.
It is easier to see what is going on in binary:

# copied from stackoverflow, prints float in binary

import struct
def binary(num):
    return ''.join(bin(ord(c)).replace('0b', '').rjust(8, '0') 
                   for c in struct.pack('!f', num))

x = np.array([0.0429911], dtype='f4')
x1 = x.astype('f2')
x2 = x1.astype('f4')

print binary(x), x
print binary(x1), x1
print binary(x2), x2

output:
00111101001100000001011101110000 [ 0.0429911]
00111101001100000010000000000000 [ 0.04299927]
00111101001100000010000000000000 [ 0.04299927]

as you can see, in binary the final result is truncated (set to 0) yet the decimal representation is longer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值