使用以下(几乎最小)示例:
import numpy as np
for x in np.arange(0,2,0.1):
print(x)
我们得到:
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6000000000000001
0.7000000000000001
0.8
0.9
1.0
1.1
1.2000000000000002
1.3
1.4000000000000001
1.5
1.6
1.7000000000000002
1.8
1.9000000000000001
作为输出。你知道吗
我知道“浮点数精度问题”是X.X000001输出的罪魁祸首,但我不明白的是为什么它有时会工作。很明显,0.3不能用一个浮点数精确地表示在基数2中,我看不到数字中没有显示一个十进制数字的模式。你知道吗
为什么Python知道0.1足以显示一个数字?是什么魔法让它去截断剩下的数字?为什么它只在某些时候起作用?你知道吗
您正在打印
numpy.float64
对象,而不是使用David Gay's dtoa algorithm的Python内置float
类型。你知道吗从version 1.14开始,numpy使用dragon4 algorithm to print floating point values,调整后的输出与用于Python
float
类型的David Gay算法的输出相同:^{} function 更详细地记录了这一点:
因此
0.2
可以通过只打印0.2
来唯一地表示,但是序列中的下一个值(0.30000000000000004
)不能,您必须包含额外的数字来唯一地表示确切的值。你知道吗这其中的如何实际上相当复杂;你可以在Bungie的Destiny游戏工程师Ryan Juckett的Printing Floating-Point Numbers series中阅读关于这方面的完整报告。你知道吗
但基本上,输出字符串的代码需要确定围绕可能的浮点数(不能解释为下一个或上一个可能的浮点数)聚集的所有十进制数的最短表示形式:
这张图片来自The Shortest Decimal String That Round-Trips: Examples和Rick Regan,它也涵盖了一些其他情况。蓝色中的数字是可能的
float64
值,绿色中的数字是十进制数字的可能表示。注意灰色的中间点标记,在浮动值周围的这两个中间点之间匹配的任何表示都是公平的,因为所有这些表示都将产生相同的值。你知道吗davidgay和Dragon4算法的目标都是找到最短的十进制字符串输出,从而再次产生完全相同的浮点值。从Python 3.1 What's New section on the David Gay approach:
相关问题 更多 >
编程相关推荐