我正在尝试以科学计数法显示 sympy 矩阵,它仅适用于小于 1 的值。我无法理解为什么
applyfunc
的行为有所不同。有更好的方法吗?
import numpy as np
from sympy import Matrix
from sympy.printing import latex
from IPython.display import display
C = np.array([
[390, 145, ],
[145, 0, ],
])*1e9
S_ij = np.linalg.inv(C)
S_scientific = Matrix(S_ij).applyfunc(lambda x: '{:.2e}'.format(float(x)))
print('this prints as desired:')
display(S_scientific) #m^2 / N
def g(x):
#shouldn't be necessary since 0 handles fine above
if abs(float(x.evalf())) < 1e-10:
return '0'
else:
return f'{float(x.evalf(8)):.2e}'
C_scientific = Matrix(C).applyfunc(g)
print()
print('this is not print in scientific notation:')
display(C_scientific)
print(C_scientific)
检查函数
g
后,输出为:
我不使用 SimPy,但这似乎对你来说可能是一个解决方法。
在这里,对于每个矩阵条目,您可以使用
Float(number, precision)
强制达到所需的精度。我想如果你不手工制作,SimPy 会回落到其标准精度,从而导致大量数字。
import numpy as np
from sympy import Matrix, Float
def formatter(x):
res = Float(x, 3)
return res
m = np.array([152000.0])
m = Matrix(m).applyfunc(formatter)