mrrclb48z
mrrclb48z

Reputation: 207

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!

Upvotes: 3

Views: 430

Answers (1)

Serenity
Serenity

Reputation: 36635

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.

Upvotes: 2

Related Questions