如何在 sympy 中舍入矩阵元素?

oys*_*ter 5 python rounding sympy

据我们所知

from sympy import *

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

A = Matrix([x, y])

print(x)
print(A.evalf())
Run Code Online (Sandbox Code Playgroud)

显示

sqrt(2)/2
Matrix([[0.707106781186548], [0.587785252292473]])
Run Code Online (Sandbox Code Playgroud)

所以

print(round(x.evalf(), 3))
print(round(y.evalf(), 3))
Run Code Online (Sandbox Code Playgroud)

显示

0.707
0.588
Run Code Online (Sandbox Code Playgroud)

但是我们如何以简洁的方式舍入矩阵中的所有元素,以便

print(roundMatrix(A, 3))
Run Code Online (Sandbox Code Playgroud)

可以显示

Matrix([[0.707], [0.588]])
Run Code Online (Sandbox Code Playgroud)

Ser*_*ity 3

为什么你不使用方法 evalf 和 args 之类的evalf(3)

from sympy import *

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

A = Matrix([x, y])

print(x)
print(A.evalf(3))
Run Code Online (Sandbox Code Playgroud)

输出

sqrt(2)/2
Matrix([[0.707], [0.588]])
Run Code Online (Sandbox Code Playgroud)