Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving Systems of Equations with SymPy

Tags:

python

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!

like image 323
Tim McLean Avatar asked Feb 25 '12 01:02

Tim McLean


People also ask

Can SymPy solve equation?

The solvers module in SymPy implements methods for solving equations. solve() is an older more mature general function for solving many types of equations.

Can Python solve systems of equations?

In Python, NumPy (Numerical Python), SciPy (Scientific Python) and SymPy (Symbolic Python) libraries can be used to solve systems of linear equations. These libraries use the concept of vectorization which allow them to do matrix computations efficiently by avoiding many for loops.


1 Answers

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.

like image 118
DSM Avatar answered Sep 21 '22 01:09

DSM