sympy:如何从“解决"中保存解决方案重用? [英] sympy: how to save solution from "solve" for reuse?
问题描述
我正在使用带有 sympy 0.7.4.1 的 python3.我不知道如何保存解决方案以备将来使用(我在手册或谷歌上找不到任何有用的东西).例如,我有一些方程 eq1,eq2 和 t1+t2+t3==0,那么我可以通过
I am using python3 with sympy 0.7.4.1. I couldn't figure out how to save solution for future use (I can't find anything useful in the manuel or on google). For example, I have some equations eq1,eq2 and t1+t2+t3==0, then I can solve the equations by
solve([t1+t2+t3,eq1,eq2],[t1,t2,t3]
但我想将解存储到 t1、t2、t3,以便我可以将它们用于其他操作.有没有简单的方法来实现这一目标?简单地使用 [t1,t2,t3]=solve([t1+t2+t3,eq1,eq2],[t1,t2,t3] 不起作用.
But I would like to store the solutions to t1,t2,t3, so that I can use them for other operations. Is there a simple way to achieve this? Simply using [t1,t2,t3]=solve([t1+t2+t3,eq1,eq2],[t1,t2,t3] does not work.
solve 的返回是
{t2: -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8, t3: 3*theta_2**2/4 - 3*theta_2*theta_3/2 + 3*theta_3**2/4, t1: -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8}
如果我添加标志 set=True,那就是
and if I add the flag set=True, it would be
([t1, t2, t3], {(-3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8, -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8, 3*theta_2**2/4 - 3*theta_2*theta_3/2 + 3*theta_3**2/4)})
对于 dict=True,它是
for dict=True, it is
[{t2: -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8, t3: 3*theta_2**2/4 - 3*theta_2*theta_3/2 + 3*theta_3**2/4, t1: -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8}]
推荐答案
首先要注意,一般来说,您可以有多种解决方案.这就是为什么 set=True 返回一组元组(而不是一个元组),而 dict=True 返回一个字典列表(而不是一个).
First note that in general, you can have multiple solutions. This is why set=True is returning a set of tuples (instead of just a single tuple), and dict=True is returning a list of dicts (instead of just one).
最简单的方法是 dict=True.要访问解决方案,请执行以下操作
The easiest one is dict=True. To access the solutions, do something like
sols = solve([t1 + t2 + t3, eq1, eq2], [t1, t2, t3])
sols[0][t1] # This is t1 in the first solution
如果有更多的解决方案,它们将是 sols[1]
、sols[2]
,等等.在每种情况下,字典中的键都是该解等于的符号,例如 t1
或 t2
.
If there were more solutions, they would be sols[1]
, sols[2]
, and so on. In each case, the key in the dictionary is the symbol that that solution equals, like t1
or t2
.
这篇关于sympy:如何从“解决"中保存解决方案重用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!