characteristicPolynomial method

  1. @override
Algebraic characteristicPolynomial()
override

The characteristic polynomial can only be computed if the matrix is square, meaning that it must have the same number of columns and rows.

The roots of the characteristic polynomial are the eigenvalues of the matrix.

If you want to find the eigenvalues of a matrix, you can compute the characteristic polynomial and solve the polynomial equation. However, for 5x5 or bigger matrices, consider using the eigenvalues method which is faster and more accurate.

A MatrixException object is thrown if the matrix isn't square.

Implementation

@override
Algebraic characteristicPolynomial() {
  // Making sure that the matrix is squared
  if (!isSquareMatrix) {
    throw const MatrixException(
      'Eigenvalues can be computed on square matrices only!',
    );
  }

  // For 1x1 matrices, directly compute it
  if (rowCount == 1) {
    return Linear.realEquation(
      b: -this(0, 0),
    );
  }

  // For 2x2 matries, use a direct formula which is faster
  if (rowCount == 2) {
    return Quadratic.realEquation(
      b: -trace(),
      c: determinant(),
    );
  }

  // For 3x3 matrices and bigger, use the Faddeev–LeVerrier algorithm
  var supportMatrix = this;
  var oldTrace = supportMatrix.trace();

  // The coefficients of the characteristic polynomial. The coefficient of the
  // highest degree is always 1.
  final coefficients = <double>[1, -trace()];

  for (var i = 1; i < rowCount; ++i) {
    final diagonal = RealMatrix.diagonal(
      rows: rowCount,
      columns: columnCount,
      diagonalValue: (1 / i) * oldTrace,
    );

    supportMatrix = this * (supportMatrix - diagonal) as RealMatrix;
    oldTrace = supportMatrix.trace();

    coefficients.add((-1 / (i + 1)) * oldTrace);
  }

  return Algebraic.fromReal(coefficients);
}