如何使用 Sympy 根据变量求解非线性等式系统?

How can I solve a system of non-linear equatoins in terms of a variable using Sympy?

我是 Sympy 的新手,我正在尝试求解以下方程组:

a*cos(theta1) + b*cos(theta2) + c*cos(theta3) + d*cos(theta4) = 0

a*sin(theta1) + b*sin(theta2) + c*sin(theta3) + d*sin(theta4) = 0

其中 theta1 是输入变量,它随时间变化(类似于 theta1 = 2*t),除 theta2 和 theta3 之外的所有其他变量都是常量。

我希望 Sympy 根据输入变量给出 theta2 和 theta3 的表达式。

我的解决方案尝试如下:

from sympy import *

a, b, c, d, theta1, theta2, theta3, theta4 = symbols("a b c d theta1 theta2 theta3 theta4")

vector_loop_equations = [a*cos(theta1) + b*cos(theta2) + c*cos(theta3) + d*cos(theta4), a*sin(theta1) + b*sin(theta2) + c*sin(theta3) + d*sin(theta4)]

vector_loop_solutions = solve(vector_loop_equations, theta2, theta3, exclude=[a,b,c,d,theta1,theta4])

print(vector_loop_solutions)

当我 运行 上面的代码时,Sympy 需要很长时间才能得出答案,以至于我从未真正看过我的代码 运行 直到完成。有没有其他方法可以求解这个非线性方程组?

尝试对所有不变的事物使用单一符号;符号越多,主化表达式所需的时间就越长。此外,转向简化和解决方案检查,因为(有很多符号)这也可能需要很长时间:

>>> from sympy.abc import A, B
>>> eqs = [
... A + b*cos(theta2) + c*cos(theta3),
... B + b*sin(theta2) + c*sin(theta3)]
>>> sol = solve(eqs, theta2, theta3, simplify=0, check=0)  # there are 8 solns

然后剔除其中带有oo的那些(它们显示为theta3的解:

>>> sol = [i for i in sol if not i[1].has(oo, -oo)]  # there are 4 solutions

对于您喜欢的任何解决方案,i,重新替换 AB 的定义:

>>> sol = [i.xreplace({
... A: a*cos(theta1)+d*cos(theta4),
... B: a*sin(theta1)+d*sin(theta4)} for i in sol]