Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I solve system of linear equations in SymPy?

Tags:

python

math

sympy

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 
like image 292
Aniket Vij Avatar asked Jul 21 '15 19:07

Aniket Vij


People also ask

How do you solve linear equations with Sympy?

import sympy as sym x,y = sym. symbols('x,y') eq1 = sym. Eq(x+y,5) eq2 = sym. Eq(x**2+y**2,17) result = sym.

Can we solve linear equations in Python?

You can either use linalg. inv() and linalg. dot() methods in chain to solve a system of linear equations, or you can simply use the solve() method. The solve() method is the preferred way.


1 Answers

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.

like image 164
Amit Kumar Avatar answered Sep 20 '22 23:09

Amit Kumar