简体   繁体   中英

How to round Matrix sqrtm in sympy?

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))

output-----------------------------------------------------------------------------------

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 want--------------------------------------------------------------------------------------

[2.000  1.000  0.000]

[1.000  2.000  1.000]

[0.000  1.000  2.000]

Thank you in advance and sorry for the bad english!

After calling sqrtm type of matrix changed and you can not use evalf :

A: <class 'sympy.matrices.dense.MutableDenseMatrix'>

B: <class 'mpmath.matrices.matrices.matrix'>

Use function chop to print matrix B in pretty format:

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))

Output:

[2.0  1.0  0.0]
[1.0  2.0  1.0]
[0.0  1.0  2.0]

Additionally you may play with nprint / nstr .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM