saulspatz
saulspatz

Reputation: 5271

Solve system of linear equations in sympy

I'm learning to use sympy.solvers.solveset.linsolve to solve a system of linear equations. I can solve the system all right, but I'm having trouble getting the results assigned to my variables. It doesn't seem to do the assignment automatically, as I would expect, but returns a one-element set set containing a tuple of the values, and I have to go through some silly contortions to get the values assigned. Here's my code:

from sympy import symbols, ones
from sympy.solvers.solveset import linsolve
A= ones(6)
A[0,0]=7
for k in range(1,6):
    A[k,k]=6
b=6*ones(6,1)
p1,p2,p3,p4,p5,p6 = symbols('p1 p2 p3 p4 p5 p6')
system = (A,b)
p=linsolve(system,p1,p2,p3,p4,p5,p6)
p1,p2,p3,p4,p5,p6=tuple(p)[0]

Surely there's a more pythonic way of doing this, isn't there?

Upvotes: 1

Views: 1388

Answers (1)

user6655984
user6655984

Reputation:

Returning a set is a central idea of solveset module (to which `linsolve' belongs). See Why do we use Sets as an output type? which includes "Why not use dicts as output?". Yes, it's awkward to deal with: one of open SymPy issues is The use of sets in solveset makes it very clumsy to get a dictionary of solutions.

I usually apply next(iter(...)) to the output of solveset and its analogues.

Your code could be simplified by not listing p1,...p6 individually, keeping it as a tuple of symbols.

syms = symbols('p1:7')
system = (A, b)
p = linsolve(system, syms)
p = next(iter(p))

Now p is the tuple (6/13, 36/65, 36/65, 36/65, 36/65, 36/65).

The older solve method can return a dict directly, but I would not recommend using it to handle a system of linear equations. Besides, SymPy development plan is to transition toward solveset, leaving solve behind.

Upvotes: 1

Related Questions