Tim McLean
Tim McLean

Reputation: 1676

Solving Systems of Equations with SymPy

I'm trying to solve a set of equations with SymPy 0.7.1:

from sympy import *
equations = [
    Eq(S('vf'), S('vi + a*t')),
    Eq(S('d'), S('vi*t + 1/2*a*t**2')),
    Eq(S('a'), S('10')),
    Eq(S('d'), S('60')),
    Eq(S('vi'), S('5'))
]
print solve(equations)

produces the correct result, but in a strange order:

[(-4, 10, 60, -35, 5), (3, 10, 60, 35, 5)]

How can I identify which value fits which variable? The variable order seems arbitrary. The documentation suggests providing additional arguments:

print solve(equations, var('a'), var('d'), var('t'), var('vi'), var('vf'))

But this seems to have no effect.

Thanks in advance for any help!

Upvotes: 15

Views: 12275

Answers (1)

DSM
DSM

Reputation: 353559

I can't figure out the outputs either. Originally I thought the problem was because you were creating new var objects rather than reusing the original ones, but that turned out not to be it. If possible, I'd simply upgrade to 0.7.1-git, where things are much better behaved:

>>> import sympy
>>> sympy.__version__
'0.7.1-git'
>>> from sympy import S, Eq, solve
>>> 
>>> vf, d, a, vi, t = S('vf d a vi t'.split())
>>> equations = [
...     Eq(vf, vi+a*t),
...     Eq(d, vi*t + a*t**2/2),
...     Eq(a, 10),
...     Eq(d, 60),
...     Eq(vi, 5)]
>>> 
>>> solve(equations)
[{vf: -35, t: -4, a: 10, vi: 5, d: 60}, {vf: 35, t: 3, a: 10, vi: 5, d: 60}]
>>> solve(equations, [a, t, vi, vf, d])
[(10, -4, 5, -35, 60), (10, 3, 5, 35, 60)]

Nice dictionaries by default, and specifying the order works.

Upvotes: 17

Related Questions