Linear Equations and Matrix Inverse

Sympy has a Matrix class and associated function that allow the symbolic solution of systems of linear equations. We shall consider a simple example to show implementation of Matrix class.
>>> from sympy import symbols, Matrix
>>> x,y,z = symbols('x,y,z')
>>> A = Matrix(([3, 7], [4, -2]))
>>> print A
Matrix([[3, 7], [4, -2]])
>>> print A.inv()
Matrix([[1/17, 7/34], [2/17, -3/34]])
>>> b = Matrix((12*z, 5*z))
>>> print b
Matrix([[12*z], [5*z]])
>>> x = A.inv()*b
>>> print x
Matrix([[59*z/34], [33*z/34]])
>>> print x.subs({z:3.3}).evalf(4)
Matrix([[5.726], [3.203]])
>>> type(x)

Alternative method of solving the same problem is to construct the system as a matrix in augmented form.
>>> from sympy import Matrix, symbols, solve_linear_system
>>> from sympy import Matrix, symbols, solve_linear_system
>>> x,y,z = symbols('x,y,z')
>>> system = Matrix(([3, 7, 12*z], [4, -2, 5*z]))
>>> print system
Matrix([[3, 7, 12*z], [4, -2, 5*z]])
>>> sol = solve_linear_system(system, x, y)
>>> print sol
{x: 59*z/34, y: 33*z/34}
>>> type(sol)
>>> for k in sol.keys():
...     print k, '=', sol[k].subs({z:3.3}).evalf(4)
...
x = 5.726
y = 3.203
A third option is the solve() method, whose arguments include the individual symbolic equations, rather than any matrices.
>>> from sympy import symbols, solve, Eq
>>> x,y,z = symbols('x,y,z')
>>> solve((Eq(3*x+7*y, 12*z), Eq(4*x-2*y, 5*z)), x, y)
{x: 59*z/34, y: 33*z/34}
>>> solve((3*x+7*y-12*z, 4*x-2*y-5*z), x, y)

{x: 59*z/34, y: 33*z/34}

Nema komentara:

Objavi komentar