admin管理员组文章数量:1122832
everyone. I've been learning floating-point truncation errors recently. But I found print(np.half(500.2))
and print(f"{np.half(500.2)}")
yield different results. Here are the logs I got in IPython.
In [11]: np.half(500.2)
Out[11]: np.float16(500.2)
In [12]: print(np.half(500.2))
500.2
In [13]: print(f"{np.half(500.2)}")
500.25
- I use
half.hpp
in c++ to compare results with numpy. It seems that500.2
should be truncated into500.25
instead of itself. - In binary formats, 500.0 is
0b0_01000_1111010000
. So the next float16 number should be0b_01000_1111010001
, which is 500.25 in deximal format.
So what makes print(np.half(500.2))
differs from print(f"{np.half(500.2)}")
? Hope to see your answers.
everyone. I've been learning floating-point truncation errors recently. But I found print(np.half(500.2))
and print(f"{np.half(500.2)}")
yield different results. Here are the logs I got in IPython.
In [11]: np.half(500.2)
Out[11]: np.float16(500.2)
In [12]: print(np.half(500.2))
500.2
In [13]: print(f"{np.half(500.2)}")
500.25
- I use
half.hpp
in c++ to compare results with numpy. It seems that500.2
should be truncated into500.25
instead of itself. - In binary formats, 500.0 is
0b0_01000_1111010000
. So the next float16 number should be0b_01000_1111010001
, which is 500.25 in deximal format.
So what makes print(np.half(500.2))
differs from print(f"{np.half(500.2)}")
? Hope to see your answers.
1 Answer
Reset to default 4print
calls __str__
, while an f-string calls __format__
. __format__
with an empty format spec is usually equivalent to __str__
, but not all types implement it that way, and numpy.half
is one of the types that implements different behavior:
In [1]: import numpy
In [2]: x = numpy.half(500.2)
In [3]: str(x)
Out[3]: '500.2'
In [4]: format(x, '')
Out[4]: '500.25'
本文标签: pythonWhat makes print(nphalf(5002)) differs from print(fquotnphalf(5002)quot)Stack Overflow
版权声明:本文标题:python - What makes `print(np.half(500.2))` differs from `print(f"{np.half(500.2)}")` - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736306011a1932797.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
0b0_01000_1111010000
is0.01526641845703125
in decimal not500.25
. Your forgot the 15 shift of exponent. seestruct.unpack('e', struct.pack('H', 0b0_01000_1111010000))
500.25 isbin(struct.unpack('H', struct.pack('e', 500.25))[0])
aka0b0_10111_1111010001
(which is the same, with exponent 8 encoded as 23, with shift of 15). But the error proves that you code floating point by hand, and not a lot do that to understand things ;-) – chrslg Commented Nov 22, 2024 at 20:06