import sympy as sym
PageRank Tutorial
PageRank Tutorial
Set up the environment. Import the sympy library.
We make a matrix using the sym.Matrix
function.
= sym.Matrix([[1,2,3],[2,1,3],[2,1,1]])
T T
\(\displaystyle \left[\begin{matrix}1 & 2 & 3\\2 & 1 & 3\\2 & 1 & 1\end{matrix}\right]\)
We can create symbolic variables, and put them into the matrix if we want…
=sym.var('x1'); x2=sym.var('x2');x3=sym.var('x3');x4=sym.var('x4') x1
x1
\(\displaystyle x_{1}\)
= sym.Matrix([[1,x2,3],[2,1,3],[2,x1,1]])
T2 T2
\(\displaystyle \left[\begin{matrix}1 & x_{2} & 3\\2 & 1 & 3\\2 & x_{1} & 1\end{matrix}\right]\)
If we input fractions, they are by default converted to floating point numbers:
= sym.Matrix([[1,x2,1/3],[2,1,3],[2,x1,1]])
T3 T3
\(\displaystyle \left[\begin{matrix}1 & x_{2} & 0.333333333333333\\2 & 1 & 3\\2 & x_{1} & 1\end{matrix}\right]\)
It’s nicer to input fractions and keep them as fractions:
= sym.Matrix([[1,x2,sym.Rational(1,3)],[2,1,3],[2,x1,1]])
T4 T4
\(\displaystyle \left[\begin{matrix}1 & x_{2} & \frac{1}{3}\\2 & 1 & 3\\2 & x_{1} & 1\end{matrix}\right]\)
We can substitute values in for variables:
5) T4.subs(x1,
\(\displaystyle \left[\begin{matrix}1 & x_{2} & \frac{1}{3}\\2 & 1 & 3\\2 & 5 & 1\end{matrix}\right]\)
We can find reduced row echelon form:
T4.rref()
(Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]),
(0, 1, 2))
This outputs the RREFand tells us which columns correspond to bound variables.
Lastly, we can do Gauss-Jordan elimination to solve a system of equations with a matrix and a right-hand-side:
2,1,3])) T4.gauss_jordan_solve(sym.Matrix([
(Matrix([
[(17*x1 - 24*x2 - 3)/(7*x1 - 12*x2 - 1)],
[ -4/(7*x1 - 12*x2 - 1)],
[(-9*x1 + 12*x2 + 3)/(7*x1 - 12*x2 - 1)]]),
Matrix(0, 1, []))
That’s messy! It’s exporting several things, but the one we want is the first.
2,1,3]))[0] T4.gauss_jordan_solve(sym.Matrix([
\(\displaystyle \left[\begin{matrix}\frac{17 x_{1} - 24 x_{2} - 3}{7 x_{1} - 12 x_{2} - 1}\\- \frac{4}{7 x_{1} - 12 x_{2} - 1}\\\frac{- 9 x_{1} + 12 x_{2} + 3}{7 x_{1} - 12 x_{2} - 1}\end{matrix}\right]\)
Now you try!
Create a matrix representing the system of equations for the “third try” in the PageRank problem:
\[ \begin{aligned} & x_{1}=\frac{x_{2}}{1}+\frac{x_{3}}{3} \\ & x_{2}=\frac{x_{1}}{2}+\frac{x_{3}}{3} \\ & x_{3}=\frac{x_{1}}{2}+\frac{x_{4}}{1} \\ & x_{4}=\frac{x_{3}}{3} . \end{aligned} \]
Now find the RREF form of this matrix. What does that tell you about the system?
Next, use the gauss_jordan_solve
. What’s surprising (or not) about these results?
Substitute a specific value to get a particular solution…