如何修改python终端显示的小数位数?

How to modify the quantity of decimals shown in the python terminal?

当我计算一个操作并显示在 python 终端 (spyder) 中时,数字有很多小数点并且很难(有时)读取结果,例如

T = array([[ 5,  5,  8,  8,  7],
           [ 7,  8,  6,  9,  6],
           [ 6,  7,  8,  9,  8],
           [ 1,  7,  1,  7,  9],
           [ 4,  2,  3,  6, 10]])

print( T @ inv(t) )

在终端我有

[[ 1.00000000e+00  4.44089210e-16  0.00000000e+00 -2.49800181e-16
   3.33066907e-16]
 [ 8.88178420e-16  1.00000000e+00  0.00000000e+00  5.55111512e-17
   0.00000000e+00]
 [ 0.00000000e+00  4.44089210e-16  1.00000000e+00 -8.32667268e-17
   0.00000000e+00]
 [ 1.77635684e-15 -4.44089210e-16  0.00000000e+00  1.00000000e+00
   1.11022302e-16]
 [-8.88178420e-16 -4.44089210e-16  3.55271368e-15 -2.22044605e-16
   1.00000000e+00]]

这是一个简单的单位矩阵。问题是

¿是否可以减少矩阵中的小数位数以显示更简单的矩阵?就像这样

np.array([[1, 0, 0, 0, 0],
          [0, 1, 0, 0, 0],
          [0, 0, 1, 0, 0],
          [0, 0, 0, 1, 0],
          [0, 0, 0, 0, 1]])

甚至更好,不仅针对矩阵,还针对终端中的所有数字

选项

'%.2f' % T @ inv(T)

报错

TypeError: only size-1 arrays can be converted to Python scalars

我正在谈论从脚本头部的初始命令更改终端中的所有显示

在 numpy 中使用这个默认函数来控制:

np.set_printoptions(suppress=True)

如果您只需要显示特定位数,请使用参数 precision:

np.set_printoptions(precision=0, suppress=True)

您可以查看更多选项here