How can I solve system of linear equations in SymPy?

In addition to the great answers given by @AMiT Kumar and @Scott, SymPy 1.0 has added even further functionalities. For the underdetermined linear system of equations, I tried below and get it to work without going deeper into sympy.solvers.solveset. That being said, do go there if curiosity leads you.

from sympy import *
x, y, z = symbols('x, y, z')
eq1 = x + y + z
eq2 = x + y + 2*z
solve([eq1-1, eq2-3], (x, y,z))

That gives me {z: 2, x: -y - 1}. Again, great package, SymPy developers!


import sympy as sp
x, y, z = sp.symbols('x, y, z')
eq1 = sp.Eq(x + y + z, 1)             # x + y + z  = 1
eq2 = sp.Eq(x + y + 2 * z, 3)         # x + y + 2z = 3
ans = sp.solve((eq1, eq2), (x, y, z))

this is similar to @PaulDong answer with some minor changes

  1. its a good practice getting used to not using import * (numpy has many similar functions)
  2. defining equations with sp.Eq() results in cleaner code later on

SymPy recently got a new Linear system solver: linsolve in sympy.solvers.solveset, you can use that as follows:

In [38]: from sympy import *

In [39]: from sympy.solvers.solveset import linsolve

In [40]: x, y, z = symbols('x, y, z')

List of Equations Form:

In [41]: linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))
Out[41]: {(-y - 1, y, 2)}

Augmented Matrix Form:

In [59]: linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))
Out[59]: {(-y - 1, y, 2)}

A*x = b Form

In [59]: M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))

In [60]: system = A, b = M[:, :-1], M[:, -1]

In [61]: linsolve(system, x, y, z)
Out[61]: {(-y - 1, y, 2)}

Note: Order of solution corresponds the order of given symbols.

Tags:

Python

Math

Sympy