Reputation: 33
I am using sympy to solve a system of linear equations and I want to use one of the solutions in further calculation. First, I wanted to pull a specific solution from the generated dictionary for my system of linear equations. I tried dict['key'] as I believe you would normally but it does work. Below is the code I tried to run.
from sympy import symbols, solve
m2,x2a,x2b,x2c,m3,m4,m5,x5a,x5b,x5c =
symbols('m2,x2a,x2b,x2c,m3,m4,m5,x5a,x5b,x5c')
solution = solve((100-m2-m3,
.980*m3-.96*(.450*100),
100*.300-m2*x2a,
1-x2a-x2b-x2c,
x2c*m2-.04*(.450*100),
m2-m4-m5,
m2*x2b-m4*.06-m5*x5b,
.940*m4-.97*(x2a*m2),
m5*x5a-.03*(x2a*m2),
1-x5a-x5b-x5c),
[m2,x2a,x2b,x2c,m3,m4,m5,x5a,x5b,x5c], dict=True)
print(solution[0]['m2'])
Upvotes: 1
Views: 87
Reputation: 880547
Sometimes there can be more than one solution to an equation or system of equations.
That is why sym.solve
returns a list of dicts, not just a dict.
Notice that print(solution)
begins with a bracket (indicating a list):
[{m2: ...}]
Therefore, to access the value of m2
for the first (and in this case only) solution, you would use
solution[0][m2]
In general, to loop through all solutions, you could use:
for s in solution:
print(s[m2])
Notice also that the dict uses SymPy Symbols as keys, not strings.
If you ever run into a similar problem again, you can investigate the problem by inspecting the .keys
attribute:
In [190]: list(solution[0].keys())
Out[190]: [m2, x2a, x2b, x2c, m3, m4, m5, x5a, x5b, x5c]
If the keys were strings, you would have seen ['m2', 'x2a', 'x2b', 'x2c', 'm3', 'm4', 'm5', 'x5a', 'x5b', 'x5c']
.
Upvotes: 2