如何控制 SymPy 中的浮点数精度?

How to control the float number precision in SymPy?

我准备了一个增广矩阵如下

A = np.round(10*np.random.randn(5,5))
I = np.eye(5)
AI = np.hstack((A, I))
AI = sy.Matrix(AI)
AI

现在执行行降维算法,逆矩阵的结果点后有很多位数,谁能告诉我如何在SymPy中控制矩阵对象的精度?

AI_rref = AI.rref()
Ainv = AI_rref[0][:,5:]
Ainv

您可以使用 applyfunc 对给定的数字进行四舍五入,或者使用 evalf/n 方法给出一定数量的有效数字。

>>> from sympy import randMatrix
>>> m = (randMatrix(3,3).row_join(eye(3))).rref()[0]
>>> m.applyfunc(lambda x: round(x, 3))
Matrix([
[1, 0, 0,  0.004, -0.022,  0.016],
[0, 1, 0,  0.015,  0.001, -0.006],
[0, 0, 1, -0.022,  0.027,    0.0]])
>>> m.n(3)
Matrix([
[1.0,   0,   0, 0.00404,  -0.0225,    0.016],
[  0, 1.0,   0,  0.0149, 0.000538, -0.00604],
[  0,   0, 1.0, -0.0216,   0.0268, 0.000228]])