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'>
我想要---------------------------------------------- -----------------------------------------
[2.000 1.000 0.000]
[1.000 2.000 1.000]
[0.000 1.000 2.000]
在此先感谢您,英语不好!
答案 0 :(得分:2)
调用sqrtm
后,矩阵类型改变,无法使用evalf
:
A:<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
。