C10 Find the characteristic polynomial of the matrix \({A = \begin{bmatrix}1&2 \\3&4 \\\end{bmatrix}}\)
Solution:
A <- matrix(c(1,2,3,4), nrow = 2, byrow = TRUE)
A
## [,1] [,2]
## [1,] 1 2
## [2,] 3 4
library(pracma)
poly1 <- charpoly(A)
poly1
## [1] 1 -5 -2
This reflects \(x^{2} -5x -2 =0\) .
To use the root solver, we need to reverse the above sequence, from lowest degree to highest:
poly2 <- rev(poly1)
poly2
## [1] -2 -5 1
This reflects \(-2 -5x + x^{2} =0\) .
soln <- polyroot(poly2)
soln
## [1] -0.3722813+0i 5.3722813-0i
This is displaying as complex numbers because the solver has (incorrectly) computed some very small complex parts:
# extract the (correct) real part of the solutions
realpart <- as.numeric(soln)
## Warning: imaginary parts discarded in coercion
realpart
## [1] -0.3722813 5.3722813
# extract the (incorrect) complex part of the solutions --
# although small, these should be exactly zero as the result is real
complexpart <- soln - realpart
complexpart
## [1] 0+3.308722e-24i 0-3.308722e-24i
Because the above equation is quadratic, we can find the precise solution using the Quadratic Formula:
\[roots=\frac { -b\pm \sqrt { (b^{ 2 }-4ac) } }{ 2a } =\frac { -(-5)\pm \sqrt { (5^{ 2 }-4\cdot 1\cdot (-2) } }{ 2\cdot 1 } =\frac { 5\pm \sqrt { (25+8) } }{ 2 } =\frac { 5\pm \sqrt { 33 } }{ 2 } \]
root1 <- (5 - sqrt(33))/2
root2 <- (5 + sqrt(33))/2
roots <- c(root1,root2)
roots
## [1] -0.3722813 5.3722813
Confirm that this is identical to the “realpart” above
roots==realpart
## [1] TRUE TRUE