简体   繁体   English

Numpy float32 的意外循环行为

[英]Unexpected round behaviour of Numpy float32

I am trying to understand how numpy handles the float32 datatype.我试图了解 numpy 如何处理 float32 数据类型。

The following code produces 0.25815687以下代码产生 0.25815687

print(np.float32(0.2581568658351898).astype(str)) # 0.25815687

But an online float converter https://www.h-schmidt.net/FloatConverter/IEEE754.html gives 0.2581568658351898193359375, Is Numpy doing something special when printing the single-precision float or there is something I missed?但是在线浮点转换器https://www.h-schmidt.net/FloatConverter/IEEE754.html给出 0.2581568658351898193359375,Numpy 在打印单精度浮点时是否做了一些特殊的事情,或者我错过了什么? Online converter result在线转换器结果

Is Numpy doing something special when printing the single-precision float or there is something I missed? Numpy 在打印单精度浮点数时是否做了一些特别的事情,或者我错过了什么?

0.2581568658351898 is not exactly encodable as a 32-bit float. 0.2581568658351898 不能完全编码为 32 位浮点数。
The closest is 0.2581568658351898193359375 or 0x1.085a46p-2最接近的是0.25815686583518981933593750x1.085a46p-2

When 0.2581568658351898193359375 is printed with reduced precision, the result is 0.25815687当以降低的精度打印0.2581568658351898193359375时,结果为0.25815687


0.2581568 658351898            Source code
0.2581568 658351898193359375   True value
0.2581568 7                    Output 

You can force the number of digits to be printed using f-strings您可以使用 f-strings 强制打印位数

print(f"{np.float32(0.2581568658351898):.25f}")

where :.25f tells the interpreter to print the value as a floating point number with 25 decimal digits.其中:.25f告诉解释器将该值打印为具有 25 位十进制数字的浮点数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM