Tut mir leid, ich bin ziemlich neu in Sympy und Python allgemein.
Ich möchte das folgende unterbestimmte lineare Gleichungssystem lösen:
x + y + z = 1
x + y + 2z = 3
SymPy hat kürzlich einen neuen linearen Systemlöser erhalten: linsolve
in sympy.solvers.solveset
. Dies können Sie wie folgt verwenden:
In [38]: from sympy import *
In [39]: from sympy.solvers.solveset import linsolve
In [40]: x, y, z = symbols('x, y, z')
Liste der Formeln:
In [41]: linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))
Out[41]: {(-y - 1, y, 2)}
Erweiterte Matrixform:
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)}
Hinweis : Die Reihenfolge der Lösung entspricht der Reihenfolge der angegebenen Symbole.
Neben den großartigen Antworten von @AMiT Kumar und @Scott hat SymPy 1.0 weitere Funktionen hinzugefügt. Für das unterbestimmte lineare Gleichungssystem versuchte ich es unten, damit es funktioniert, ohne tiefer in sympy.solvers.solveset
zu gehen. Gehen Sie dorthin, wenn Sie neugierig sind.
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))
Das gibt mir {z: 2, x: -y - 1}
. Wieder ein tolles Paket, SymPy-Entwickler!
Sie können in Matrixform Ax=b
lösen (in diesem Fall ein unterbestimmtes System, aber wir können solve_linear_system
verwenden):
from sympy import Matrix, solve_linear_system
x, y, z = symbols('x, y, z')
A = Matrix(( (1, 1, 1, 1), (1, 1, 2, 3) ))
solve_linear_system(A, x, y, z)
{x: -y - 1, z: 2}
Oder neu schreiben als (meine Bearbeitung, nicht sympy):
[x]= [-1] [-1]
[y]= y[1] + [0]
[z]= [0] [2]
Im Falle eines Quadrats A
könnten wir b
definieren und A.LUsolve(b)
verwenden.
Ein weiteres Beispiel für lineare Matrixsystemgleichungen, nehmen wir an, wir lösen für dieses System:
In SymPy
könnten wir so etwas tun:
>>> import sympy as sy
... sy.init_printing()
>>> a, b, c, d = sy.symbols('a b c d')
... A = sy.Matrix([[a-b, b+c],[3*d + c, 2*a - 4*d]])
... A
⎡ a - b b + c ⎤
⎢ ⎥
⎣c + 3⋅d 2⋅a - 4⋅d⎦
>>> B = sy.Matrix([[8, 1],[7, 6]])
... B
⎡8 1⎤
⎢ ⎥
⎣7 6⎦
>>> A - B
⎡ a - b - 8 b + c - 1 ⎤
⎢ ⎥
⎣c + 3⋅d - 7 2⋅a - 4⋅d - 6⎦
>>> sy.solve(A - B, (a, b, c, d))
{a: 5, b: -3, c: 4, d: 1}
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))
dies ist ähnlich wie bei @PaulDong mit einigen geringfügigen Änderungen
import *
nicht zu verwenden (numpy hat viele ähnliche Funktionen).sp.Eq()
führt später zu sauberem Code