How to round Matrix elements in sympy?

Viewed 1659

As we know

from sympy import *

x = sin(pi/4)
y = sin(pi/5)

A = Matrix([x, y])

print(x)
print(A.evalf())

displays

sqrt(2)/2
Matrix([[0.707106781186548], [0.587785252292473]])

So

print(round(x.evalf(), 3))
print(round(y.evalf(), 3))

displays

0.707
0.588

But how can we round all the elements in a Matrix in a terse way, so that

print(roundMatrix(A, 3))

can displays

Matrix([[0.707], [0.588]])
2 Answers

Why you do not use method evalf with args like evalf(3)?

from sympy import *

x = sin(pi/4)
y = sin(pi/5)

A = Matrix([x, y])

print(x)
print(A.evalf(3))

Output

sqrt(2)/2
Matrix([[0.707], [0.588]])

This works for me

# Z is a matrix
from functools import partial

round3 = partial(round, ndigits=3)
Z.applyfunc(round3)
# if you want to save the result
# Z = Z.applyfunc(round3)
Related