import sympy as sym # This library is used for symbolic computing
# Make two variables x and y
x, y = sym.symbols("x y")
print x # this will simply print the text "x"
# Make matrices and vectors using symbols
F = sym.Matrix([x*y, x**2 - y]) # vector of length 2
print F
A = sym.Matrix([[x*y, x + y],
[x - y, x*y**2]]) # matrix of size 2x2
print A
# Evaluate symbolic expressions / using numbers instead of x and y
print F.subs({x:1, y:2}) # set x=1 and y=2 NB: only in this line
print A.subs({x:1, y:2}) # set x=1 and y=2
# Compute Jacobian of symbolic expression
J = F.jacobian([x, y]) # must give the variables we differentiate wrt
print J
# Solve Ax = b
b = sym.Matrix([x + y, x - y])
print A.solve(b) # symbolic solution
print A.solve(b).subs({x:1, y:2}) # evaluated solution
# Can also evaluate first, and then solve the system (This is faster)
A_s = A.subs({x:1, y:2})
b_s = b.subs({x:1, y:2})
print A_s.solve(b_s)
print A_s.solve(b_s).norm() # compute norm of answer