问题
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]
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.
The return from solve 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}
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)})
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}]
回答1:
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).
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
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.
来源:https://stackoverflow.com/questions/21371093/sympy-how-to-save-solution-from-solve-for-reuse