Skip to content

Instantly share code, notes, and snippets.

@unixpickle
Created May 17, 2022 16:34
Show Gist options
  • Save unixpickle/eab1d8bf2ca195c33f3cc67c1f38ed3a to your computer and use it in GitHub Desktop.
Save unixpickle/eab1d8bf2ca195c33f3cc67c1f38ed3a to your computer and use it in GitHub Desktop.
Characteristic polynomial
"""
Compute the closed-form characteristic polynomial of a 4x4 matrix.
"""
import sympy
syms = sympy.symbols('a b c d e f g h i j k l m n o p')
mat = sympy.Matrix([[syms[i+j*4] for i in range(4)] for j in range(4)])
print(sympy.collect((mat - sympy.eye(4)*sympy.symbols('x')).det(), 'x'))
# a*f*k*p - a*f*l*o - a*g*j*p + a*g*l*n + a*h*j*o - a*h*k*n - b*e*k*p + b*e*l*o + b*g*i*p - b*g*l*m - b*h*i*o + b*h*k*m + c*e*j*p - c*e*l*n - c*f*i*p + c*f*l*m + c*h*i*n - c*h*j*m - d*e*j*o + d*e*k*n + d*f*i*o - d*f*k*m - d*g*i*n + d*g*j*m + x**4 + x**3*(-a - f - k - p) + x**2*(a*f + a*k + a*p - b*e - c*i - d*m + f*k + f*p - g*j - h*n + k*p - l*o) + x*(-a*f*k - a*f*p + a*g*j + a*h*n - a*k*p + a*l*o + b*e*k + b*e*p - b*g*i - b*h*m - c*e*j + c*f*i + c*i*p - c*l*m - d*e*n + d*f*m - d*i*o + d*k*m - f*k*p + f*l*o + g*j*p - g*l*n - h*j*o + h*k*n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment