David Choi
David Choi

Reputation: 115

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

I am really new to using Sympy, and I am trying to solve the following system of equations:

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

where theta1 is the input variable, which changes over time (something like theta1 = 2*t), and all of the other variables except for theta2 and theta3 are constants.

I want Sympy to give me expressions for theta2 and theta3 in terms of the input variable.

My attempt at a solution is as follows:

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)

When I run the code above, it takes such a long time for Sympy to come up with an answer that I have never actually seen my code run till completion. Is there any other way of solving this system of non-linear equations?

Upvotes: 1

Views: 65

Answers (1)

smichr
smichr

Reputation: 19145

Try to use a single symbol for all that is not variable; the more symbols there are the longer it will take to mainpulate the expressions. Also, turn of simplification and solultion checking since (with many symbols) this can take a long time, too:

>>> 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

Then eliminate those with oo in them (which appear as the solution for theta3:

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

For any of the solutions you like, i, re-substitute in the definitions for A and B:

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

Upvotes: 0

Related Questions