How to round Matrix elements in sympy?
from sympy import *
from mpmath import *
A=Matrix([[5,4,1],
          [4,6,4],
          [1,4,5]])
print(A)
print(type(A.evalf(3)))
B=sqrtm(A)
print(B)
print(type(B))
print(B.evalf(3))Matrix([[5, 4, 1], [4, 6, 4], [1, 4, 5]])
<class 'sympy.matrices.dense.MutableDenseMatrix'>
Traceback (most recent call last):
  File "C:/Users/xxx/.PyCharmCE2018.2/config/scratches/scratch_9.py", line 11, in <module>
    print(B.evalf(3))
AttributeError: 'matrix' object has no attribute 'evalf'
[                 2.0  1.0  3.33606965638267e-20]
[                 1.0  2.0                   1.0]
[3.34095591577049e-20  1.0                   2.0]
<class 'mpmath.matrices.matrices.matrix'>I
[2.000  1.000  0.000]
[1.000  2.000  1.000]
[0.000  1.000  2.000]提前感谢您,并为我糟糕的英语表示抱歉!
发布于 2018-12-28 13:00:39
调用sqrtm后,矩阵类型发生变化,不能使用evalf
答:<class 'sympy.matrices.dense.MutableDenseMatrix'>
B:<class 'mpmath.matrices.matrices.matrix'>
使用函数chop以漂亮的格式打印矩阵B:
from sympy import *
from mpmath import *
A=Matrix([[5,4,1],
          [4,6,4],
          [1,4,5]])
print(A)
B=sqrtm(A)
print(chop(B))输出:
[2.0  1.0  0.0]
[1.0  2.0  1.0]
[0.0  1.0  2.0]此外,您还可以使用nprint/nstr。
https://stackoverflow.com/questions/53923323
复制相似问题