正如我们所知
from sympy import *
x = sin(pi/4)
y = sin(pi/5)
A = Matrix([x, y])
print(x)
print(A.evalf())
显示
sqrt(2)/2
Matrix([[0.707106781186548], [0.587785252292473]])
所以
print(round(x.evalf(), 3))
print(round(y.evalf(), 3))
显示
0.707
0.588
但是,我们如何才能以简洁的方式将矩阵中的所有元素取整,从而使
print(roundMatrix(A, 3))
可以显示
Matrix([[0.707], [0.588]])
为什么不将方法evalf与evalf(3)
等参数一起使用?
from sympy import *
x = sin(pi/4)
y = sin(pi/5)
A = Matrix([x, y])
print(x)
print(A.evalf(3))
输出
sqrt(2)/2
Matrix([[0.707], [0.588]])
这适用于我的
# 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)
from sympy import *
roundMatrix = lambda m, n: Matrix([[round(m[x, y], n) for y in range(m.shape[1])] for x in range(m.shape[0])])
x = sin(pi/4)
y = sin(pi/5)
A = Matrix([x, y])
print(x)
print(roundMatrix(A.evalf(), 3))`