Python numpy 浮点数精度问题
在复现FP(fictitious play, Iterative solution of games by fictitious play-page393)算法的时候,迭代到中间发现没法复现paper里的结果,发现是numpy矩阵运算浮点数精度的问题。
- 具体问题
矩阵和向量相乘
\[\begin{pmatrix}
3 & 1 & 1 & 1
\end{pmatrix}
\times \begin{pmatrix}
3 & 1.1 & 1.2 \\
1.3 & 2 & 0 \\
0 & 1 & 3.1 \\
2 & 1.5 & 1.1
\end{pmatrix}
= \begin{pmatrix}
12.3 & 7.8 & 7.8
\end{pmatrix}
\]
3 & 1 & 1 & 1
\end{pmatrix}
\times \begin{pmatrix}
3 & 1.1 & 1.2 \\
1.3 & 2 & 0 \\
0 & 1 & 3.1 \\
2 & 1.5 & 1.1
\end{pmatrix}
= \begin{pmatrix}
12.3 & 7.8 & 7.8
\end{pmatrix}
\]
然后取argmin
想得到第一个7.8的index,也就是1。但由于精度的问题,导致两个7.8实际不一样大,取到了第二个7.8的index。
具体问题代码为
import numpy as np
x = np.matrix([3,1,1,1])*np.matrix([[3,1.1,1.2],[1.3,2,0],[0,1,3.1],[2,1.5,1.1]])
print('matrix: ',x)
print('value: ',x[0,0],x[0,1],x[0,2])
print('index: ',np.argmin(x))
得到
matrix: [[12.3 7.8 7.8]]
value: 12.3 7.800000000000001 7.799999999999999
index: 2
可以发现明明相同的两个7.8由于精度变成了两个大小不同的数,所以argmin
得到了2。
- 解决办法
二进制固有的问题,只能自己手动近似,用保留小数点位数消除误差。
如这里保留5位小数:
import numpy as np
x = np.round(np.matrix([3,1,1,1])*np.matrix([[3,1.1,1.2],[1.3,2,0],[0,1,3.1],[2,1.5,1.1]]),5)
print('matrix: ',x)
print('value: ',x[0,0],x[0,1],x[0,2])
print('index: ',np.argmin(x))
得到
matrix: [[12.3 7.8 7.8]]
value: 12.3 7.8 7.8
index: 1
- 注意事项
这个办法不能解决所有问题,毕竟每个问题精度要求不一样。但由于计算机二进制的原因,没法从根本上解决,只能通过近似的方式,具体问题具体解决。