# Main: Solve Equations in Python

The following tutorials are an introduction to solving linear and nonlinear equations with Python. The solution to linear equations is through matrix operations while sets of nonlinear equations require a solver to numerically find a solution.

#### Source Code for Linear Solutions

import numpy as np

A = np.array([ [3,-9], [2,4] ])
b = np.array([-42,2])
z = np.linalg.solve(A,b)
print(z)

M = np.array([ [1,-2,-1], [2,2,-1], [-1,-1,2] ])
c = np.array([6,1,1])
y = np.linalg.solve(M,c)
print(y)

#### Source Code for Nonlinear Solution

from numpy import *
from scipy.optimize import *

def myFunction(z):
x = z[0]
y = z[1]
w = z[2]

F = empty((3))
F[0] = pow(x,2)+pow(y,2)-20
F[1] = y - pow(x,2)
F[2] = w + 5 - x*y
return F

zGuess = array([1,1,1])
z = fsolve(myFunction,zGuess)
print(z)

#### Symbolic Solutions

Sympy is a package for symbolic solutions in Python that can be used to solve systems of equations.

$$2x^2+y+z=1$$ $$x+2y+z=c_1$$ $$-2*x+y=-z$$

import sympy as sym
sym.init_printing()
x,y,z = sym.symbols('x,y,z')
c1 = sym.Symbol('c1')
f = sym.Eq(2*x**2+y+z,1)
g = sym.Eq(x+2*y+z,c1)
h = sym.Eq(-2*x+y,-z)sourceend:)

sym.solve([f,g,h],(x,y,z))

When solved in an IPython environment such as a Jupyter notebook, the result is displayed as:

$$x=-\frac{1}{2}+\frac{\sqrt{3}}{2}$$ $$y=c_1 - \frac{3 \sqrt{3}}{2} +\frac{3}{2}$$ $$z=-c_1 - \frac{5}{2} +\frac{5 \sqrt{3}}{2}$$

and a second solution:

$$x=-\frac{1}{2}-\frac{\sqrt{3}}{2}$$ $$y=c_1 + \frac{3 \sqrt{3}}{2} +\frac{3}{2}$$ $$z=-c_1 - \frac{5}{2} -\frac{5 \sqrt{3}}{2}$$

The same approach applies to linear or nonlinear equations.