Home:ALL Converter>How can I solve system of linear equations in SymPy?

How can I solve system of linear equations in SymPy?

Ask Time:2015-07-22T03:12:00         Author:Aniket Vij

Json Formatter

Sorry, I am pretty new to sympy and python in general.

I want to solve the following underdetermined linear system of equations:

x + y + z = 1 
x + y + 2z = 3

Author:Aniket Vij,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/31547657/how-can-i-solve-system-of-linear-equations-in-sympy
Amit Kumar :

SymPy recently got a new Linear system solver: linsolve in sympy.solvers.solveset, you can use that as follows:\n\nIn [38]: from sympy import *\n\nIn [39]: from sympy.solvers.solveset import linsolve\n\nIn [40]: x, y, z = symbols('x, y, z')\n\n\nList of Equations Form: \n\nIn [41]: linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))\nOut[41]: {(-y - 1, y, 2)}\n\n\nAugmented Matrix Form:\n\nIn [59]: linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))\nOut[59]: {(-y - 1, y, 2)}\n\n\nA*x = b Form\n\nIn [59]: M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))\n\nIn [60]: system = A, b = M[:, :-1], M[:, -1]\n\nIn [61]: linsolve(system, x, y, z)\nOut[61]: {(-y - 1, y, 2)}\n\n\nNote: Order of solution corresponds the order of given symbols.",
2015-07-21T19:21:29
Ali80 :

import sympy as sp\nx, y, z = sp.symbols('x, y, z')\neq1 = sp.Eq(x + y + z, 1) # x + y + z = 1\neq2 = sp.Eq(x + y + 2 * z, 3) # x + y + 2z = 3\nans = sp.solve((eq1, eq2), (x, y, z))\n\n\nthis is similar to @PaulDong answer with some minor changes\n\n\nits a good practice getting used to not using import * (numpy has many similar functions)\ndefining equations with sp.Eq() results in cleaner code later on\n",
2019-02-14T17:50:09
PaulDong :

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.\n\nfrom sympy import *\nx, y, z = symbols('x, y, z')\neq1 = x + y + z\neq2 = x + y + 2*z\nsolve([eq1-1, eq2-3], (x, y,z))\n\n\nThat gives me {z: 2, x: -y - 1}. \nAgain, great package, SymPy developers!",
2016-10-04T08:58:42
Aziz Alto :

Another example on matrix linear system equations, lets assume we are solving for this system:\n\n\n\nIn SymPy we could do something like:\n\n>>> import sympy as sy\n... sy.init_printing()\n\n>>> a, b, c, d = sy.symbols('a b c d')\n... A = sy.Matrix([[a-b, b+c],[3*d + c, 2*a - 4*d]])\n... A\n\n⎡ a - b b + c ⎤\n⎢ ⎥\n⎣c + 3⋅d 2⋅a - 4⋅d⎦\n\n\n>>> B = sy.Matrix([[8, 1],[7, 6]])\n... B\n\n⎡8 1⎤\n⎢ ⎥\n⎣7 6⎦\n\n\n>>> A - B\n\n⎡ a - b - 8 b + c - 1 ⎤\n⎢ ⎥\n⎣c + 3⋅d - 7 2⋅a - 4⋅d - 6⎦\n\n\n>>> sy.solve(A - B, (a, b, c, d))\n{a: 5, b: -3, c: 4, d: 1}\n",
2016-10-19T04:02:52
yy