Solving Systems of Equations with SymPy

亡梦爱人 提交于 2020-01-01 04:15:10

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/9440337/solving-systems-of-equations-with-sympy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!