用SymPy求解方程组

时间:2021-12-24 12:36:56

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

我正在尝试用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 个解决方案

#1


15  

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:

我也无法弄清楚输出。最初我认为这个问题是因为你正在创建新的var对象而不是重用原始对象,但事实证明并非如此。如果可能的话,我只需升级到0.7.1-git,其中表现得更好:

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

默认情况下很好的词典,并指定顺序有效。

#1


15  

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:

我也无法弄清楚输出。最初我认为这个问题是因为你正在创建新的var对象而不是重用原始对象,但事实证明并非如此。如果可能的话,我只需升级到0.7.1-git,其中表现得更好:

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

默认情况下很好的词典,并指定顺序有效。