SymPy:在两个不同向量中获得特殊解决方案

问题描述 投票:0回答:1

我想使用 SymPy 求解 Ax = 0 的特殊解:

使用此代码:

from sympy import solve

Vec = sp.Matrix(np.matrix([[1,5,7,9],
                 [0,4,1,7],
                 [2,-2,11,-3]]))

print(sp.linsolve( (Vec, sp.Matrix([[0],[0],[0],[0]])) ))

我得到了正确的输出:

{(-23*tau0/4 - tau1/4, -tau0/4 - 7*tau1/4, tau0, tau1)}

但是,我想要两个不同向量中的两个特殊解决方案(对应于 tau0 和 tau1 的倍数),例如:

有没有办法为每个 tau 获得这两个单独的特殊解向量,而不是将它们全部放在一起?

python sympy linear-algebra
1个回答
0
投票

不完全是您要寻找的答案,但查看 docs

sp.linsolve
返回“包含有序值元组的有限集”。

没有固有的 sympy 方法可以单独获得特殊的解决方案。

另一种选择是使用正则表达式将它们分开,请参阅示例代码(您可以根据自己的喜好进行格式化):

import regex as re
import sympy as sp
import numpy as np
Vec = sp.Matrix(np.matrix([[1,5,7,9],
                 [0,4,1,7],
                 [2,-2,11,-3]]))

ans_ = sp.linsolve( (Vec, sp.Matrix([[0],[0],[0],[0]])) )

# there might be a better regex to do this

# replace tau0
sol1 = [re.sub(r"(\S*(tau0)\S*.)", "", str(temp)) for temp in list(ans_.args)[0]]
sol1 = [0 if x=='tau0' else x for x in sol1] 

# replace tau1
sol2 = [re.sub(r"((-+).\S*(tau1)\S*)", "", str(temp)) for temp in list(ans_.args)[0]]
sol2 = [0 if x=='tau1' else x for x in sol2]
sol1, sol2

输出:

(['- tau1/4', '- 7*tau1/4', 0, 'tau1'], ['-23*tau0/4 ', '-tau0/4 ', 'tau0', 0])
© www.soinside.com 2019 - 2024. All rights reserved.