Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions Sources/AngouriMath/Core/Entity/Omni/Entity.Matrix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,71 @@ public Entity AsScalar()
);
private LazyPropertyA<Entity?> determinant;

/// <summary>
/// The characteristic polynomial of this square matrix, <c>det(x I - A)</c> in the
/// variable <paramref name="x"/>, written as a polynomial in it with each coefficient
/// simplified: for <c>[[a, b], [c, d]]</c> it is <c>x^2 - (a + d) x + a d - b c</c>.
/// <see langword="null"/> where the matrix is not square, or where <paramref name="x"/>
/// already occurs in it, since then the polynomial would not be one in <paramref name="x"/>.
/// </summary>
/// <remarks>
/// <para>
/// The monic one: its leading coefficient is <c>1</c>, the next is minus the trace and
/// the constant term is <c>(-1)^n det(A)</c>. <c>det(A - x I)</c>, the other convention,
/// is <c>(-1)^n</c> times it; the monic one is the one the Cayley–Hamilton theorem and
/// the minimal polynomial are stated with.
/// </para>
/// <para>
/// It is the <see cref="Determinant"/> of <c>x I - A</c>, which divides by nothing: its
/// entries are polynomials in <c>x</c> and the entries of <c>A</c>, and Bareiss'
/// elimination and Laplace expansion both leave a polynomial. Gaussian elimination would
/// leave its pivots, which are polynomials in <c>x</c>, as divisions, and the
/// characteristic polynomial -- defined everywhere -- would have no value where one of
/// them vanished. <a href="https://github.com/asc-community/AngouriMath/issues/381">#381</a>
/// </para>
/// </remarks>
/// <example>
/// <code>
/// Console.WriteLine(MathS.Matrix(new Entity[,] { { 1, 2 }, { 3, 4 } }).CharacteristicPolynomial("x"));
/// </code>
/// Prints
/// <code>
/// x ^ 2 - 5 * x - 2
/// </code>
/// </example>
public Entity? CharacteristicPolynomial(Variable x)
{
if (!IsSquare || ContainsNode(x))
return null;
var shifted = MathS.Matrix(RowCount, ColumnCount, (row, column) => (row == column ? (Entity)x : 0) - this[row, column]);
if (shifted.Determinant is not { } shiftedDeterminant)
return null;
// Read off power by power, so that each coefficient is simplified on its own
// rather than the whole left as the determinant's expansion wrote it.
var byPower = Functions.Algebra.AnalyticalSolving.PolynomialSolver
.GatherMonomialInformation<PeterO.Numbers.EInteger, Functions.TreeAnalyzer.PrimitiveInteger>(
Sumf.LinearChildren(shiftedDeterminant.Expand()), x);
if (byPower is null)
return shiftedDeterminant;
Entity? polynomial = null;
foreach (var power in byPower.Keys.OrderByDescending(static power => power))
{
var coefficient = byPower[power].Simplify();
if (coefficient == 0)
continue;
Entity monomial = power.IsZero ? 1 : power.Equals(PeterO.Numbers.EInteger.One) ? x : MathS.Pow(x, Number.Integer.Create(power));
// A term whose coefficient reads more simply negated is subtracted, as it is
// written by hand: x^2 - 5 x, and x^2 - (a + d) x rather than + (-a - d) x.
var negated = (-coefficient).Simplify();
var subtracted = polynomial is not null
&& (coefficient is Number.Real { EDecimal.IsNegative: true } || negated.Complexity < coefficient.Complexity);
var magnitude = subtracted ? negated : coefficient;
var term = magnitude == 1 ? monomial : power.IsZero ? magnitude : magnitude * monomial;
polynomial = polynomial is null ? term : subtracted ? polynomial - term : polynomial + term;
}
return polynomial ?? 0;
}

/// <summary>Returns an inverse matrix if it exists</summary>
public Matrix? Inverse => inverse.GetValue(static @this =>
{
Expand Down
69 changes: 69 additions & 0 deletions Sources/Tests/UnitTests/Algebra/CharacteristicPolynomialTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//
// Copyright (c) 2019-2026 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//

using AngouriMath;
using AngouriMath.Extensions;
using Xunit;
using static AngouriMath.Entity.Number;

namespace AngouriMath.Tests.Algebra
{
/// <summary>
/// The characteristic polynomial of a square matrix, <c>det(x I - A)</c>.
/// https://github.com/asc-community/AngouriMath/issues/381
/// </summary>
[Trait("Area", "Algebra")]
public sealed class CharacteristicPolynomialTest
{
private static Entity Of(Entity[,] entries) => MathS.Matrix(entries).CharacteristicPolynomial("x")!;

/// <summary>The textbook one: <c>x^2 - (a + d) x + a d - b c</c>, the trace and the determinant.</summary>
[Fact]
public void TwoByTwoIsTheTraceAndTheDeterminant()
=> Assert.Equal(Integer.Zero,
(Of(new Entity[,] { { "a", "b" }, { "c", "d" } }) - "x^2 - (a + d) * x + a * d - b * c".ToEntity()).Simplify());

[Theory]
[InlineData("x ^ 2 - 5 * x - 2")]
public void ItIsWrittenAsAPolynomialInTheVariable(string written)
{
Assert.Equal(written, Of(new Entity[,] { { 1, 2 }, { 3, 4 } }).Stringize());
Assert.Equal("x ^ 2 - (a + d) * x + d * a - b * c", Of(new Entity[,] { { "a", "b" }, { "c", "d" } }).Stringize());
}

/// <summary>
/// A value everywhere, at the diagonal entries included: there Gaussian elimination's
/// pivots, <c>x - 1</c> and the like, vanish, and a polynomial computed through them had
/// no value.
/// </summary>
[Theory]
[InlineData(1)]
[InlineData(4)]
public void ItHasAValueAtEveryPoint(int at)
=> Assert.Equal(Integer.Create(-6), Of(new Entity[,] { { 1, 2 }, { 3, 4 } }).Substitute("x", at).Evaled);

/// <summary>
/// A triangular matrix's eigenvalues are its diagonal entries, so they are the roots, and
/// the constant term is <c>(-1)^n det(A)</c>: here <c>-(2 · 3 · -1)</c>, which is <c>6</c>.
/// </summary>
[Fact]
public void ATriangularMatrixHasItsDiagonalForRoots()
{
var polynomial = Of(new Entity[,] { { 2, 5, 7 }, { 0, 3, 1 }, { 0, 0, -1 } });
foreach (var root in new[] { 2, 3, -1 })
Assert.Equal(Integer.Zero, polynomial.Substitute("x", root).Evaled);
Assert.Equal(Integer.Create(6), polynomial.Substitute("x", 0).Evaled);
}

[Fact]
public void OnlyForASquareMatrixWithoutTheVariable()
{
Assert.Null(MathS.Matrix(new Entity[,] { { 1, 2, 3 }, { 4, 5, 6 } }).CharacteristicPolynomial("x"));
Assert.Null(MathS.Matrix(new Entity[,] { { "x", 1 }, { 0, 1 } }).CharacteristicPolynomial("x"));
}
}
}
1 change: 1 addition & 0 deletions Sources/Tests/UnitTests/Common/PublicApi.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1410,6 +1410,7 @@ AngouriMath.Entity+Matrix+EntityTensorWrapperOperations.ToString(AngouriMath.Ent
AngouriMath.Entity+Matrix.<Clone>$() : AngouriMath.Entity+Matrix
AngouriMath.Entity+Matrix.Adjugate { } : AngouriMath.Entity+Matrix
AngouriMath.Entity+Matrix.AsScalar() : AngouriMath.Entity
AngouriMath.Entity+Matrix.CharacteristicPolynomial(AngouriMath.Entity+Variable) : AngouriMath.Entity
AngouriMath.Entity+Matrix.Codomain { } : AngouriMath.Core.Domain
AngouriMath.Entity+Matrix.ColumnCount { } : System.Int32
AngouriMath.Entity+Matrix.Determinant { } : AngouriMath.Entity
Expand Down
Loading