同情 pprint sin(a_n) 和 s(a_n)

Get sympy to pprint sin(a_n) with s(a_n)

我试图让 sympy 打印带有第一个字母而不是缩短项的三角函数的矩阵,以节省 space。所以 sin(a_1) 看起来像 sa_1。现在我正在打印文本然后 运行 查找和替换。 (我是编程新手。)到目前为止,这是行不通的:

from sympy import sin as s
from sympy import cos as c

# declaring symbolic variables:
sin, cos, = sym.symbols('s, c')

  #An example Matrix
  T = Matrix([[c(theta), -s(theta), 0, a],
                [s(theta) * c(alpha), c(theta) * c(alpha), -s(alpha), -s(alpha) * d],
                [s(theta) * s(alpha), c(theta) * s(alpha), c(alpha), c(alpha) * d],
                [0, 0, 0, 1]])
#T04 was a sympy symbol matrix solution 
T_000 = str(print_latex(T04))
T_000 = str(T04)
T_000 = T_000.replace('sin', 's')
T_000 = T_000.replace('cos', 'c')
print('T000\n')
pprint(T_000)
T_001 = Matrix([[(-s(theta_1) * s(theta_2) + c(theta_1) * c(theta_2)) * c(theta_3) + (
            -s(theta_1) * c(theta_2) - s(theta_2) * c(theta_1)) * s(theta_3),
                 -(-s(theta_1) * s(theta_2) + c(theta_1) * c(theta_2)) * s(theta_3) + (
                             -s(theta_1) * c(theta_2) - s(theta_2) * c(theta_1)) * c(theta_3), 0,
                 L_1 * c(theta_1) + L_2 * (-s(theta_1) * s(theta_2) + c(theta_1) * c(theta_2))], [
                    (-s(theta_1) * s(theta_2) + c(theta_1) * c(theta_2)) * s(theta_3) + (
                                s(theta_1) * c(theta_2) + s(theta_2) * c(theta_1)) * c(theta_3),
                    (-s(theta_1) * s(theta_2) + c(theta_1) * c(theta_2)) * c(theta_3) - (
                                s(theta_1) * c(theta_2) + s(theta_2) * c(theta_1)) * s(theta_3), 0,
                    L_1 * s(theta_1) + L_2 * (s(theta_1) * c(theta_2)
                                              + s(theta_2) * c(theta_1))], [0, 0, 1, d_4], [0, 0, 0, 1]])
print('\nT001\n')
pprint(T_001)

T_000.replace(sin, s)
print('T000\n', T_000)

它总是打印完整的“sin”和“cos”名称。

有两种常用的方法来替换表达式中的函数(在这种情况下,表达式是矩阵 T)。一种是使用 replace function, the other is to use the subs 函数。两者中的任何一个都可以用来实现将 sin/cos 替换为其他功能的相同目标。

在下面的代码中,我们将函数 s(它是 sin 的别名)替换为未定义的函数 s1(其符号名称为 s). cc1.

也是如此
from sympy import *

# s,c act as aliases to sin,cos
s = sin
c = cos

# the intended short-hand functions used to replace sin/cos later on
s1 = Function('s')
c1 = Function('c')

a,d,theta,alpha = symbols('a d \theta \alpha')

T = Matrix([
    [c(theta), -s(theta), 0, a],
    [s(theta) * c(alpha), c(theta) * c(alpha), -s(alpha), -s(alpha) * d],
    [s(theta) * s(alpha), c(theta) * s(alpha), c(alpha), c(alpha) * d],
    [0, 0, 0, 1]
])

T_1 = T.replace(s,s1).replace(c,c1)
T_2 = T.subs({s:s1,c:c1})

display(T_1)
display(T_2)

输出:

此post中使用的代码是also available here