diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 4719df037..88781c1f4 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -481,6 +481,29 @@ before v3, which decides exact comparisons exactly (#1019 §10). Two decimals th | `sqrt(5)^1000 = 5^500` | `False` | stays written | | `sqrt(2) < sqrt(2) + 10^(-150)` | `False` | stays written | +### A system keeps the solutions where it divided by zero + +**Silent: an incomplete answer becomes the whole solution set, or no answer.** Solving a system that the Gröbner +basis does not take, such as one with fewer equations than unknowns or one that is not polynomial, an equation was solved for its last unknown by dividing by a coefficient in the +others, and the solutions where that coefficient is zero were dropped. A factor free of that unknown is now +solved apart, and where the leading coefficient can be zero the system is solved again with it zero. Where a +root divides by another unknown and that case cannot be solved, the system is declined. Measured on master +`9b75a2678` and on this branch ([#2738](https://github.com/asc-community/AngouriMath/issues/2738)). + +| `MathS.Equations(...).Solve(...)` | Was (master) | Now | +|---|---|---| +| `x*y - x` for `x, y` | `[[t_1, t_1 / t_1]]` | `[[0, t_1], [t_2, 1]]` | +| `x*y - x` for `y, x` | `[[t_1, 0]]` | `[[1, t_1], [t_2, 0]]` | +| `x^2 + x*y - x + y - 2` for `x, y` | `[[t_1, -(t_1 ^ 2 + -t_1 + -2) / (t_1 + 1)]]` | `[[-1, t_1], [t_2, -(t_2 + -2)]]` | +| `x*z + 2*x`, `y - 2` for `x, y, z` | `[[t_1, 2, -2 * t_1 / t_1]]` | `[[0, 2, t_1], [t_2, 2, -2]]` | +| `x*z + y` for `x, y, z` | `[[t_1, t_2, -t_2 / t_1]]` | `[[t_2, t_3, -t_3 / t_2], [0, 0, t_1]]` | +| `sin(x)*y - sin(x)` for `x, y` | `[[t_1, sin(t_1) / sin(t_1)]]` | `[[t_2, sin(t_2) / sin(t_2)], [2 * pi * n_1, t_1], [pi + 2 * pi * n_1, t_1]]` | +| `y^x - 2` for `x, y` | `[[t_1, 2 ^ (1 / t_1)]]` | `null` | +| `x*y - x`, `2*x*y - 2*x` for `x, y` | `[[t_1, t_1 / t_1]]` | `[[0, t_1], [0, 1], [t_1, 1]]` | +| `sin(x)*y - sin(x)`, `x - y` for `x, y` | `[[1, 1]]` | `[[2 * pi * n_1, 2 * pi * n_1], [pi + 2 * pi * n_1, pi + 2 * pi * n_1], [1, 1]]` | +| `sqrt(2)*x*y - sqrt(2)*x`, `x^2 + y - 4` for `x, y` | `[[sqrt(3), 1], [-sqrt(3), 1]]` | `[[0, 4], [sqrt(3), 1], [-sqrt(3), 1]]` | +| `e^x*y - 2*e^x + x*y - 2*x`, `x - y` for `x, y` | `[[2, 2]]`, without `x = y = -W(1)` | `null` | + ### A square system is answered exactly whichever order its equations are in **Not silent: a decimal answer is now exact, and a refused system has an answer.** The eliminator took the last diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs index 505cfc295..174514bcd 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs @@ -474,6 +474,27 @@ private static Entity AtASamplePoint(Entity residual, HashSet own) return NonSquareSystemSolver.Solve(constraining, unknowns, ledger); equations = constraining; } + // A factor free of the last unknown is solved apart from what is left of its equation, + // as NonSquareSystemSolver does: x y - x, x + y - 3 solved for y as x/x left out (0, 3). + // A branch can leave an unknown that no equation mentions, which is that solver's shape. + // https://github.com/asc-community/AngouriMath/issues/2738 + if (ledger is not null && NonSquareSystemSolver.FactorFreeOfTheLast(equations, vars.ToArray(), vars.Length) is var (at, factor, remainder)) + { + var all = new List>(); + foreach (var part in new[] { factor, remainder }) + { + var branch = new List(equations); + branch[at] = part; + var unknowns = vars.ToArray(); + var rows = unknowns.Any(unknown => !branch.Any(equation => equation.ContainsNode(unknown))) + ? NonSquareSystemSolver.SolveOrNone(branch, unknowns, ledger) + : InSolveSystem(branch, vars, nameSource, ledger); + if (rows is null) + return null; + all.AddRange(rows); + } + return all; + } var var = vars[^1]; if (equations.Count == 1) { @@ -536,7 +557,24 @@ private static Entity AtASamplePoint(Entity residual, HashSet own) var result = new List>(); var told = true; - foreach (var sol in sols) + // The roots divide by the leading coefficient in `var`, and where it can be + // zero that case is solved apart, as NonSquareSystemSolver does; roots that + // cannot be told complete leave the candidate undecided. + // https://github.com/asc-community/AngouriMath/issues/2738 + if (ledger is not null) + { + var unknowns = vars.ToArray(); + if (!NonSquareSystemSolver.RootsAreComplete(equations[i], unknowns, unknowns.Length, sols, rest, out var degenerate)) + told = false; + else if (degenerate is not null) + { + if (NonSquareSystemSolver.SolveOrNone(degenerate, unknowns, ledger, generic: true) is { } found) + result.AddRange(found); + else + told = false; + } + } + foreach (var sol in told ? sols : new List()) { var below = rest.Select(eq => eq.Substitute(var, sol)).ToList(); if (InSolveSystem(below, remainingVars, nameSource, ledger) is not { } rows) diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/NonSquareSystemSolver.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/NonSquareSystemSolver.cs index 7b20ae3fe..11af06768 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/NonSquareSystemSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/NonSquareSystemSolver.cs @@ -7,6 +7,8 @@ using AngouriMath.Core.Budgets; using AngouriMath.Core.Exceptions; +using AngouriMath.Functions; +using PeterO.Numbers; using System; using static AngouriMath.Entity; using static AngouriMath.Entity.Number; @@ -50,6 +52,17 @@ internal static class NonSquareSystemSolver /// values in their order for each family, or where none were found. /// internal static List>? Solve(List equations, Variable[] variables, BudgetLedger ledger) + => SolveOrNone(equations, variables, ledger) is { Count: > 0 } families ? families : null; + + /// + /// As , but empty where the system has no solutions, and + /// only where that could not be told. Where + /// , an equation left with none of the unknowns, in symbols that + /// are not, is taken as away from zero, as solving a x = 1 takes a: the system + /// is the case where a divisor is zero, and a condition on the symbols alone is that case + /// within the case. + /// + internal static List>? SolveOrNone(List equations, Variable[] variables, BudgetLedger ledger, bool generic = false) { // One parameter per unknown that is left free, the same in every branch. Each is // minted against the equations and the parameters already minted, since CreateUnique @@ -65,7 +78,7 @@ Variable ParameterFor(int index) return parameters[index] = parameter; } - if (Eliminate(equations, variables, variables.Length, ParameterFor, ledger) is not { Count: > 0 } families) + if (Eliminate(equations, variables, variables.Length, ParameterFor, ledger, generic) is not { } families) return null; var own = new HashSet(equations.SelectMany(equation => equation.Vars)); foreach (var family in families) @@ -95,7 +108,7 @@ Variable ParameterFor(int index) /// where that could not be told. /// private static List>? Eliminate(List equations, Variable[] variables, int count, - Func parameterFor, BudgetLedger ledger) + Func parameterFor, BudgetLedger ledger, bool generic, int rotations = 0) { // Charged as InSolveSystem charges it: one unit for each candidate explored. if (!ledger.Spend()) @@ -109,7 +122,7 @@ Variable ParameterFor(int index) { var told = true; foreach (var equation in equations) - switch (Holds(equation)) + switch (Holds(equation, generic)) { case false: return new(); @@ -126,7 +139,7 @@ Variable ParameterFor(int index) // root to go on with, so the system was declined. It is decided by value and dropped. // Only a zero is: `x - x - 1` is away from zero at every point and stays, and the // system that left it has no solution. https://github.com/asc-community/AngouriMath/issues/2601 - var constraining = equations.Where(equation => !Vanishes(equation, System.Array.Empty())).ToList(); + var constraining = equations.Where(equation => !Vanishes(equation, WholeIn(equation))).ToList(); if (constraining.Count < equations.Count) equations = constraining; @@ -139,6 +152,28 @@ Variable ParameterFor(int index) return new() { free }; } + // An equation that none of the unknowns left is in, and that is a number away from + // zero, leaves no solution however the rest is solved. + if (equations.Any(equation => !MentionsAny(equation, variables, count) && Holds(equation, generic) == false)) + return new(); + + // A factor free of the last unknown is solved apart from what is left of its + // equation, and the system holds where either is zero. Solved as it stands, the + // equation would be divided by that factor: x y - x for y is y = x/x, which leaves out + // every solution with x = 0. https://github.com/asc-community/AngouriMath/issues/2738 + if (FactorFreeOfTheLast(equations, variables, count) is var (at, factor, remainder)) + { + var whereTheFactorIs = new List(equations); + whereTheFactorIs[at] = factor; + var whereTheRestIs = new List(equations); + whereTheRestIs[at] = remainder; + if (Eliminate(whereTheFactorIs, variables, count, parameterFor, ledger, generic) is not { } first + || Eliminate(whereTheRestIs, variables, count, parameterFor, ledger, generic) is not { } second) + return null; + first.AddRange(second); + return first; + } + var variable = variables[count - 1]; // The equation with the fewest occurrences of the unknown first, which is solved by // inverting it and has the plainest roots: of `cos(x) = sin(x)` and `x = pi/4`, the @@ -158,16 +193,49 @@ Variable ParameterFor(int index) continue; var rest = new List(equations); rest.RemoveAt(i); - if (EachRoot(roots, rest, variables, count, parameterFor, ledger) is { } solutions) + var whereTheLeadingIsZero = new List>(); + if (!RootsAreComplete(equations[i], variables, count, roots, rest, out var degenerate)) + continue; + if (degenerate is not null) + { + if (Eliminate(degenerate, variables, count, parameterFor, ledger, generic: true) is not { } found) + continue; + whereTheLeadingIsZero = found; + } + if (EachRoot(roots, rest, variables, count, parameterFor, ledger, generic) is { } solutions) + { + solutions.AddRange(whereTheLeadingIsZero); return solutions; + } // This equation's roots left a question that could not be told. Another // equation's may not: `sin(x) = 0` gives x = 2 pi n_1, where `x = 0` gives 0. } if (candidates.Count > 0) - return null; + { + // Another unknown may be told first, from an equation this one is not in: with + // x^2 = 0 beside y^3 + x y^2 = a, y is a cube root that divides by x, and x is 0. + // The unknowns are rotated, so that the one before this is eliminated first, at + // most once round. https://github.com/asc-community/AngouriMath/issues/2738 + if (rotations >= count - 1 || !equations.Any(equation => !equation.ContainsNode(variable) && MentionsAny(equation, variables, count - 1))) + return null; + var rotated = (Variable[])variables.Clone(); + for (var index = count - 1; index > 0; index--) + rotated[index] = variables[index - 1]; + rotated[0] = variable; + Variable RotatedParameterFor(int index) => parameterFor(index == 0 ? count - 1 : index < count ? index - 1 : index); + if (Eliminate(equations, rotated, count, RotatedParameterFor, ledger, generic, rotations + 1) is not { } found) + return null; + foreach (var family in found) + { + var first = family[0]; + family.RemoveAt(0); + family.Insert(count - 1, first); + } + return found; + } // Nothing constrains this unknown, so it is a parameter in every solution of the rest. - var others = Eliminate(equations, variables, count - 1, parameterFor, ledger); + var others = Eliminate(equations, variables, count - 1, parameterFor, ledger, generic); others?.ForEach(family => family.Add(parameterFor(count - 1))); return others; } @@ -177,35 +245,190 @@ Variable ParameterFor(int index) /// turn, or where that could not be told for one of them. /// private static List>? EachRoot(List roots, List rest, Variable[] variables, int count, - Func parameterFor, BudgetLedger ledger) + Func parameterFor, BudgetLedger ledger, bool generic) { var variable = variables[count - 1]; var solutions = new List>(); foreach (var root in roots) { var substituted = rest.Select(equation => equation.Substitute(variable, root)).ToList(); - if (Eliminate(substituted, variables, count - 1, parameterFor, ledger) is not { } families) + if (Eliminate(substituted, variables, count - 1, parameterFor, ledger, generic) is not { } families) return null; foreach (var family in families) { var value = SolutionParameters.Apart(root, family, substituted, variable); for (var index = 0; index < count - 1; index++) value = value.Substitute(variables[index], family[index]); - family.Add(value.InnerSimplified); + value = value.InnerSimplified; + // A root with no value where the rest put the others, as 2/(x + 1) at x = -1, + // gives no solution there. Where it divided by the leading coefficient, the + // case is solved apart. https://github.com/asc-community/AngouriMath/issues/2738 + if (!value.Vars.Any() && value.Evaled is Complex { IsNaN: true } or Complex { IsFinite: false }) + continue; + family.Add(value); solutions.Add(family); } } return solutions; } + /// + /// The symbols in that stand for every whole number, as the + /// n_1 of a periodic root does: sin(x) after x = pi n_1 is zero for each. + /// + private static List WholeIn(Entity expression) + => expression.Vars.Where(name => SolutionParameters.Current?.SetOf(name) == MathS.Sets.Z).Distinct().ToList(); + + /// + /// Whether mentions any of the first + /// of . + /// + private static bool MentionsAny(Entity expression, Variable[] variables, int count) + { + for (var index = 0; index < count; index++) + if (expression.ContainsNode(variables[index])) + return true; + return false; + } + + /// + /// A factor of one of that is free of the last unknown but not + /// of the others, with the equation's index and what is left of it, or + /// where no equation has one. x y - x for y is + /// x (y - 1), and solving it for y as it stands divides by x. + /// https://github.com/asc-community/AngouriMath/issues/2738 + /// + internal static (int Index, Entity Factor, Entity Remainder)? FactorFreeOfTheLast(List equations, Variable[] variables, int count) + { + var variable = variables[count - 1]; + for (var i = 0; i < equations.Count; i++) + { + var equation = equations[i]; + if (!equation.ContainsNode(variable) || !MentionsAny(equation, variables, count - 1)) + continue; + // A polynomial over the rationals: the content in the last unknown, the greatest + // common divisor of its coefficients. + var symbols = equation.Vars.Distinct().ToArray(); + if (symbols.Length <= MultivariatePolynomial.MaxVariables) + { + var indices = new Dictionary(symbols.Length); + for (var index = 0; index < symbols.Length; index++) + indices[symbols[index]] = index; + if (MultivariatePolynomial.TryParse(equation, indices) is { } polynomial) + { + var main = indices[variable]; + var rest = Enumerable.Range(0, symbols.Length).Where(index => index != main).ToList(); + if (polynomial.DegreeIn(main) > 0 + && PolynomialGcd.ContentIn(polynomial, main, rest, 0) is { IsConstant: false } content + && Enumerable.Range(0, count - 1).Any(index => indices.TryGetValue(variables[index], out var at) && content.DegreeIn(at) > 0) + && polynomial.DivideExact(content) is { } primitive + // Multiplied back, so that a split is only made where it is one. + && primitive.Multiply(content) is { } product && product.SameAs(polynomial)) + return (i, content.ToEntity(symbols), primitive.ToEntity(symbols)); + continue; + } + } + // Otherwise the factors of a product, as x e^y - x is not but x (e^y - 1) is. + if (equation is not Mulf) + continue; + var factors = Mulf.LinearChildren(equation); + var free = factors.Where(factor => !factor.ContainsNode(variable) && MentionsAny(factor, variables, count - 1) + && factor is not Powf(_, Real { IsNegative: true })).ToList(); + if (free.Count == 0) + continue; + var others = factors.Where(factor => !free.Contains(factor)).ToList(); + return (i, Mulf.Multiply(free.ToArray()), others.Count == 0 ? Integer.One : Mulf.Multiply(others.ToArray())); + } + return null; + } + + /// + /// Whether , the roots of in the last of + /// the first unknowns, are every root wherever they have a value, + /// with the system left to solve where they have none, or + /// where there is no such place. + /// + /// + /// A root divides by the leading coefficient in the unknown, and where that is zero the + /// equation has a lower degree and solutions of its own: x z + y for z is + /// -y/x, and x = y = 0 leaves z free. That case is the system + /// with the leading coefficient and the lower terms. Past the + /// quadratic formula a root can divide by more than the leading coefficient, and is taken + /// only where it divides by no unknown; and so is a root of an equation that is not a + /// polynomial in the unknown: e^(x y) = 1 for y is 2 pi i n / x, and + /// every y is a solution at x = 0. + /// https://github.com/asc-community/AngouriMath/issues/2738 + /// + internal static bool RootsAreComplete(Entity equation, Variable[] variables, int count, IReadOnlyList roots, + List rest, out List? degenerate) + { + degenerate = null; + var variable = variables[count - 1]; + if (CoefficientsIn(equation, variable) is not { Count: > 0 } coefficients || coefficients.Keys.Last().Sign <= 0) + return !roots.Any(root => DividesByAnUnknown(root, variables, count - 1)); + var degree = coefficients.Keys.Last(); + var leading = coefficients[degree]; + if (degree.CompareTo(2) > 0 && coefficients.Values.Any(coefficient => MentionsAny(coefficient, variables, count - 1)) + && roots.Any(root => DividesByAnUnknown(root, variables, count - 1))) + return false; + if (MentionsAny(leading, variables, count - 1)) + { + var lower = coefficients.Where(term => term.Key.CompareTo(degree) < 0) + .Select(term => term.Key.IsZero ? term.Value : term.Value * MathS.Pow(variable, Integer.Create(term.Key))) + .ToList(); + degenerate = new List(rest) { leading, lower.Count == 0 ? Integer.Zero : Sumf.Sum(lower) }; + } + return true; + } + + /// + /// The coefficients of as a polynomial in + /// , by power, with none that is zero for every value, or + /// where it is not a polynomial in it. + /// + private static SortedDictionary? CoefficientsIn(Entity equation, Variable variable) + { + if (!TreeAnalyzer.TryGetPolynomial(equation, variable, out var monomials) || monomials.Keys.Any(power => power.Sign < 0)) + return null; + var coefficients = new SortedDictionary(); + foreach (var (power, coefficient) in monomials) + if (!Vanishes(coefficient, WholeIn(coefficient))) + coefficients[power] = coefficient; + return coefficients; + } + + /// + /// Whether divides by an expression in the first + /// of , and so may have no value + /// where the equation it solves still has solutions: e^(x y) = 1 for y is + /// 2 pi i n / x, which has no value at x = 0, where every y is a + /// solution. https://github.com/asc-community/AngouriMath/issues/2738 + /// + private static bool DividesByAnUnknown(Entity root, Variable[] variables, int count) + { + if (root is Providedf(var value, _)) + root = value; + return root.Nodes.Any(node => node switch + { + Divf(_, var divisor) => MentionsAny(divisor, variables, count), + Powf(var @base, var exponent) => MentionsAny(@base, variables, count) + && !(exponent.Evaled is Real { IsNegative: false } && !exponent.Vars.Any()), + _ => false, + }); + } + /// /// Whether , with no unknown left in it, holds: /// where it simplifies to zero, where it is a - /// number away from zero, and where neither can be told. + /// number away from zero, and where neither can be told. Where + /// , one in symbols that are not unknowns is away from zero, as + /// says. /// - private static bool? Holds(Entity equation) + private static bool? Holds(Entity equation, bool generic = false) { - if (Vanishes(equation, System.Array.Empty())) + if (generic && Holds(equation) is null && equation.Vars.Any() && WholeIn(equation).Count == 0) + return false; + if (Vanishes(equation, WholeIn(equation))) return true; if (equation.Vars.Any() || equation.Evaled is not Complex value || value.IsNaN) return null; diff --git a/Sources/Tests/UnitTests/Algebra/SolveTest/AnUnderdeterminedSystemKeepsWhereADivisorIsZeroTest.cs b/Sources/Tests/UnitTests/Algebra/SolveTest/AnUnderdeterminedSystemKeepsWhereADivisorIsZeroTest.cs new file mode 100644 index 000000000..4bbe644cd --- /dev/null +++ b/Sources/Tests/UnitTests/Algebra/SolveTest/AnUnderdeterminedSystemKeepsWhereADivisorIsZeroTest.cs @@ -0,0 +1,142 @@ +// +// 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 System.Linq; +using Xunit; +using static AngouriMath.Entity; + +namespace AngouriMath.Tests.Algebra.SolveTest +{ + /// + /// An underdetermined system lost the solutions where the coefficient it divided by was zero. + /// x y - x for x, y was [[t_1, t_1 / t_1]]: solving for y divided by + /// x, and every solution with x = 0 was left out, as was the family's own point at + /// t_1 = 0. A factor free of the unknown being solved for is now solved apart, and where + /// the leading coefficient can be zero the system is solved again with it zero. + /// https://github.com/asc-community/AngouriMath/issues/2738 + /// + [Trait("Area", "Algebra")] + public sealed class AnUnderdeterminedSystemKeepsWhereADivisorIsZeroTest + { + private static Matrix? Solve(string[] equations, string[] variables) + => MathS.Equations(equations.Select(e => e.ToEntity()).ToArray()) + .Solve(variables.Select(v => (Variable)v).ToArray()); + + /// + /// Whether some row takes the value : its columns that are a bare + /// parameter are set from the point, and every other column must then evaluate to it. + /// + private static bool Represents(Matrix solutions, string[] variables, double[] point) + { + var unknowns = variables.Select(v => (Variable)v).ToHashSet(); + for (var row = 0; row < solutions.RowCount; row++) + foreach (var whole in new[] { -1, 0, 1 }) + { + var parameters = Enumerable.Range(0, variables.Length) + .Where(column => solutions[row, column] is Variable name && !unknowns.Contains(name)) + .ToDictionary(column => (Variable)solutions[row, column], column => point[column]); + var matches = true; + for (var column = 0; column < variables.Length && matches; column++) + { + var value = solutions[row, column]; + foreach (var (name, at) in parameters) + value = value.Substitute(name, at); + // An n_1 stands for every whole number, and a few are tried. + foreach (var name in value.Vars.Where(name => name.Name.StartsWith("n_")).ToList()) + value = value.Substitute(name, whole); + matches = value.Evaled is Number.Complex { IsNaN: false } number + && ((Number.Real)(number - point[column]).Abs()).EDecimal.ToDouble() < 1e-9; + } + if (matches) + return true; + } + return false; + } + + // Each point is a solution, residual 0 by hand, and the first is the one master left out. + [Theory] + [InlineData(new[] { "x*y - x" }, new[] { "x", "y" }, new[] { 0.0, 5, 5, 1, 0, 1 })] + [InlineData(new[] { "x*y - x" }, new[] { "y", "x" }, new[] { 1.0, 5, 5, 0, 1, 0 })] + [InlineData(new[] { "x*y - 2*x - y + 2" }, new[] { "x", "y" }, new[] { 1.0, 5, 5, 2, 1, 2 })] + [InlineData(new[] { "x^2*y - x^2" }, new[] { "x", "y" }, new[] { 0.0, 5, 5, 1 })] + [InlineData(new[] { "x^2 + x*y - x + y - 2" }, new[] { "x", "y" }, new[] { -1.0, 5, 5, -3, -1, 3 })] + [InlineData(new[] { "x*z + 2*x", "y - 2" }, new[] { "x", "y", "z" }, new[] { 0.0, 2, 5, 5, 2, -2, 0, 2, -2 })] + [InlineData(new[] { "x*y - x", "2*x*y - 2*x" }, new[] { "x", "y" }, new[] { 0.0, 5, 5, 1 })] + // No common factor: the leading coefficient x is zero where y is, and then z is free. + [InlineData(new[] { "x*z + y" }, new[] { "x", "y", "z" }, new[] { 0.0, 0, 5, 2, -4, 2 })] + [InlineData(new[] { "sin(x)*y - sin(x)" }, new[] { "x", "y" }, new[] { 0.0, 5, 2, 1 })] + // A square system is eliminated the same way, and lost the same points. + [InlineData(new[] { "x*y - x", "x + y - 3" }, new[] { "x", "y" }, new[] { 0.0, 3, 2, 1 })] + [InlineData(new[] { "sqrt(2)*x*y - sqrt(2)*x", "x^2 + y - 4" }, new[] { "x", "y" }, new[] { 0.0, 4, 1.7320508075688772, 1 })] + [InlineData(new[] { "x*y + x - y/2 - 1/2", "2*x*y + 2*x - y - 1" }, new[] { "x", "y" }, new[] { 0.5, 5, 5, -1 })] + public void EverySolutionIsInARow(string[] equations, string[] variables, double[] points) + { + var solutions = Solve(equations, variables); + Assert.NotNull(solutions); + for (var start = 0; start < points.Length; start += variables.Length) + { + var point = points.Skip(start).Take(variables.Length).ToArray(); + Assert.True(Represents(solutions!, variables, point), $"({string.Join(", ", point)}) is not in {solutions}"); + } + // And every row is a solution, wherever it has a value. + var unknowns = variables.Select(v => (Variable)v).ToHashSet(); + foreach (var at in new[] { 0, 1.37, -2.3 }) + for (var row = 0; row < solutions!.RowCount; row++) + foreach (var text in equations) + { + Entity residual = text.ToEntity(); + for (var column = 0; column < variables.Length; column++) + residual = residual.Substitute(variables[column], solutions[row, column]); + foreach (var name in residual.Vars.Where(name => !unknowns.Contains(name) && name.Name.StartsWith("t_")).ToList()) + residual = residual.Substitute(name, at); + if (residual.Vars.Any(name => name.Name.StartsWith("n_"))) + residual = residual.Substitute(residual.Vars.First(name => name.Name.StartsWith("n_")), 1); + var value = Assert.IsAssignableFrom(residual.Evaled); + if (value.IsNaN && at == 0) + continue; + Assert.True(((Number.Real)value.Abs()).EDecimal.ToDouble() < 1e-9, $"{residual} in {solutions}"); + } + } + + // t_1 / t_1 had no value at t_1 = 0, where the system has a solution. With the common + // factor solved apart no row divides at all. + [Theory] + [InlineData(new[] { "x*y - x" }, new[] { "x", "y" })] + [InlineData(new[] { "x*y - x" }, new[] { "y", "x" })] + [InlineData(new[] { "x*y - 2*x - y + 2" }, new[] { "x", "y" })] + [InlineData(new[] { "x^2 + x*y - x + y - 2" }, new[] { "x", "y" })] + [InlineData(new[] { "x*z + 2*x", "y - 2" }, new[] { "x", "y", "z" })] + public void NoRowLosesItsOwnPoint(string[] equations, string[] variables) + { + var solutions = Solve(equations, variables); + Assert.NotNull(solutions); + Entity all = solutions!; + foreach (var name in all.Vars.Where(name => name.Name.StartsWith("t_")).ToList()) + all = all.Substitute(name, 0); + for (var row = 0; row < solutions.RowCount; row++) + for (var column = 0; column < variables.Length; column++) + Assert.False(((Matrix)all)[row, column].Evaled is Number.Complex { IsNaN: true }, $"{solutions}"); + } + + // x = y = pi n as well as x = y = 1; the first was left out. + [Fact] + public void APeriodicFactorOfASquareSystemIsKept() + { + var solutions = Solve(new[] { "sin(x)*y - sin(x)", "x - y" }, new[] { "x", "y" }); + Assert.NotNull(solutions); + Assert.Contains(solutions!.Vars, name => name.Name.StartsWith("n_")); + Assert.True(Represents(solutions, new[] { "x", "y" }, new[] { 1.0, 1 }), $"{solutions}"); + } + + // Every y is a solution at x = 0, and solving for y as 2 pi i n / x cannot say so. + [Fact] + public void ARootThatDividesByAnUnknownIsDeclined() + => Assert.Null(Solve(new[] { "e^(x*y) - 1" }, new[] { "x", "y" })); + } +}