Skip to content

Commit c2a75a9

Browse files
A square system is not answered with rows that are no solution (#2125)
EquationSystem.Solve returned every row the eliminator found for a square system without putting it back into the system. Solving one equation can widen it, so a row could be no solution: sqrt(y) = x is solved for y as x^2, and sqrt(y) - x, x + 1 was answered [[-1, 1]], where sqrt(1) - (-1) is 2. Each row is now put back into the equations as the caller wrote them: - A row that leaves an equation with no symbol in it a number away from zero is no solution for any value of anything, and is dropped. The test is the one that drops a spurious root of one equation, taken out of IsSpurious as StatementSolver.IsEvidenceAgainst. A system left with no row is null. - A row with symbols in it is tried at one value of them: the system's own symbols at positive values that are not whole, and a parameter the row brings with it, t_1 or n_1, at 2, since an n_1 stands for whole numbers only. A row that fails there may hold for other values, as sqrt(t^2) = t does for positive t, so the system is declined as null instead of being answered by the other rows alone. - Anything else is kept, as a root of one equation is. Measured, each probed on 2.6.0 and on this branch: sqrt(y) - x; x + 1 [[-1, 1]] -> null sqrt(y) - x; y - 4 [[2, 4], [-2, 4]] -> [[2, 4]] ln(x) + ln(y); x - y [[-1, -1], [1, 1]] -> [[1, 1]] sqrt(y) - x; y - a [[sqrt(a), (sqrt(a)) ^ 2], [-sqrt(a), (-sqrt(a)) ^ 2]] -> null Unchanged: x*y - a; x - y, x^2 - a; y - x, sin(x) - y; y - 1/2 with its rows in n_1, and both cubic systems in SolveSystem, whose nine rows each hash the same. Cost, the 1024-row uncoupled quartics: 1.50 s -> 1.58-1.67 s. The symbolic cubic system: 111 -> 372 ms, its nine rows of nested radicals evaluated at the sample point. Fixes #2123 Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 429f5f6 commit c2a75a9

5 files changed

Lines changed: 199 additions & 3 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,24 @@ A not-equal written `<>` is read as `not (a = b)`, and printed that way.
4242

4343
## Unreleased — since 2.6.0
4444

45+
### A square system is not answered with rows that are no solution
46+
47+
**Silent: a row that is no solution is gone, and a system with a row that fails for some values is `null`.**
48+
`EquationSystem.Solve` with as many equations as unknowns returned every row the elimination found, without putting it
49+
back into the system. Solving one equation can widen it: `sqrt(y) = x` is solved for `y` as `x^2`, which is no
50+
solution where `x` is negative. Each row is now put back into the system as written. A row that leaves an equation
51+
with no symbol in it a number away from zero is dropped, as a root of one equation is, and a system left with no row
52+
is `null`. A row with symbols in it is tried at one value of them, and where it fails there the system is declined as
53+
`null`, since the row may still hold for other values
54+
([#2123](https://github.com/asc-community/AngouriMath/issues/2123)).
55+
56+
| Input | Was (2.6.0) | Now |
57+
|---|---|---|
58+
| `MathS.Equations("sqrt(y) - x", "x + 1").Solve("x", "y")` | `[[-1, 1]]` | `null`: `sqrt(1) - (-1)` is 2 |
59+
| `MathS.Equations("sqrt(y) - x", "y - 4").Solve("x", "y")` | `[[2, 4], [-2, 4]]` | `[[2, 4]]` |
60+
| `MathS.Equations("ln(x) + ln(y)", "x - y").Solve("x", "y")` | `[[-1, -1], [1, 1]]` | `[[1, 1]]`: `ln(-1) + ln(-1)` is `2 pi i` |
61+
| `MathS.Equations("sqrt(y) - x", "y - a").Solve("x", "y")` | `[[sqrt(a), (sqrt(a)) ^ 2], [-sqrt(a), (-sqrt(a)) ^ 2]]` | `null`: the second row is a solution only at `a = 0` |
62+
4563
### A system with more or fewer equations than unknowns is solved or declined
4664

4765
**Not silent: what was an exception is an answer or `null`.** `EquationSystem.Solve` threw

‎Sources/.editorconfig‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
264264
[Tests/UnitTests/Algebra/SolveTest/ParametricSystemTest.cs]
265265
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
266266

267+
[Tests/UnitTests/Algebra/SolveTest/SpuriousSystemRowTest.cs]
268+
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
269+
267270
[Tests/UnitTests/Common/LambdaArrowSyntaxTest.cs]
268271
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
269272

‎Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,8 @@ internal static Set Solve(Entity equation, Variable x)
9696

9797
internal static Matrix? SolveSystem(IEnumerable<Entity> inputEquations, ReadOnlySpan<Variable> vars)
9898
{
99-
var equations = new List<Entity>(inputEquations.Select(equation => equation.InnerSimplified));
99+
var written = inputEquations.ToList();
100+
var equations = new List<Entity>(written.Select(equation => equation.InnerSimplified));
100101

101102
// Triangularising first, where the system is polynomial over Q and the answer can
102103
// be checked exactly. Eliminating in radicals -- which is what InSolveSystem below
@@ -155,7 +156,13 @@ internal static Set Solve(Entity equation, Variable x)
155156
throw new AngouriBugException("InSolveSystem incorrect output");
156157
if (res.Count == 0)
157158
return null;
158-
var tb = new MatrixBuilder(res, initVarCount);
159+
// Each row is put back into the system as the caller wrote it, as a root of one
160+
// equation is: `sqrt(y) = x` is solved for `y` as `x^2`, which is no solution
161+
// where `x` is negative, and `sqrt(y) - x`, `x + 1` was answered [[-1, 1]].
162+
// https://github.com/asc-community/AngouriMath/issues/2123
163+
if (RowsThatHold(written, variables, res) is not { Count: > 0 } rows)
164+
return null;
165+
var tb = new MatrixBuilder(rows, initVarCount);
159166
return tb.ToMatrix();
160167
}
161168
finally
@@ -164,6 +171,72 @@ internal static Set Solve(Entity equation, Variable x)
164171
}
165172
}
166173

174+
/// <summary>
175+
/// The rows of <paramref name="rows"/> that satisfy each of <paramref name="equations"/>,
176+
/// or <see langword="null"/> where a row is shown not to for some value of the symbols
177+
/// left in it.
178+
/// </summary>
179+
/// <remarks>
180+
/// <para>
181+
/// A row is dropped on the evidence a root of one equation is dropped on,
182+
/// <see cref="StatementSolver.IsEvidenceAgainst"/>: an equation that, with the row put
183+
/// in, has no symbol left and is a number away from zero. Such a row is no solution for
184+
/// any value of anything, so dropping it loses none.
185+
/// </para>
186+
/// <para>
187+
/// A row with symbols left in it is tried at one value of them, and one that fails there
188+
/// declines the system instead of being dropped. It may hold for other values, as
189+
/// <c>sqrt(t^2) = t</c> does for every positive <c>t</c>, and the rows left would read as
190+
/// all of the solutions. A symbol of the system's own is tried at a positive value that
191+
/// is not whole, and a parameter that a row brings with it, a <c>t_1</c> or an
192+
/// <c>n_1</c>, at a whole one, since an <c>n_1</c> stands for those only.
193+
/// </para>
194+
/// <para>
195+
/// Anything else is kept, as a root of one equation is: a residual that cannot be
196+
/// evaluated, or one too small next to its terms to be told from rounding.
197+
/// </para>
198+
/// </remarks>
199+
private static List<List<Entity>>? RowsThatHold(List<Entity> equations, Variable[] variables, List<List<Entity>> rows)
200+
{
201+
var own = new HashSet<Variable>(equations.SelectMany(equation => equation.Vars));
202+
var replacements = new Dictionary<Variable, Entity>();
203+
var kept = new List<List<Entity>>(rows.Count);
204+
foreach (var row in rows)
205+
{
206+
replacements.Clear();
207+
for (var index = 0; index < variables.Length; index++)
208+
replacements[variables[index]] = row[index];
209+
var residuals = equations.Select(equation => equation.Substitute(replacements)).ToList();
210+
if (residuals.Any(residual => !residual.Vars.Any() && StatementSolver.IsEvidenceAgainst(residual)))
211+
continue;
212+
if (residuals.Any(residual => residual.Vars.Any() && StatementSolver.IsEvidenceAgainst(AtASamplePoint(residual, own))))
213+
return null;
214+
kept.Add(row);
215+
}
216+
return kept;
217+
}
218+
219+
/// <summary>
220+
/// <paramref name="residual"/> with each symbol of <paramref name="own"/> at a positive
221+
/// value that is not whole, and every other symbol at 2.
222+
/// </summary>
223+
private static Entity AtASamplePoint(Entity residual, HashSet<Variable> own)
224+
{
225+
var values = new[] { (137, 100), (61, 100), (223, 100), (191, 100), (83, 100), (113, 100) };
226+
var index = 0;
227+
foreach (var symbol in residual.Vars.ToList())
228+
{
229+
Entity value = Integer.Create(2);
230+
if (own.Contains(symbol))
231+
{
232+
var (numerator, denominator) = values[index++ % values.Length];
233+
value = Rational.Create(numerator, denominator);
234+
}
235+
residual = residual.Substitute(symbol, value);
236+
}
237+
return residual;
238+
}
239+
167240
/// <summary>Solves system of equations</summary>
168241
/// <param name="equations"><see cref="List{T}"/> of <see cref="Entity"/></param>
169242
/// <param name="vars">

‎Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,17 @@ private static bool IsSpurious(Entity equation, Variable x, Entity root)
123123
return true;
124124
if (root.Vars.Any())
125125
return false;
126-
var substituted = equation.Substitute(x, root);
126+
return IsEvidenceAgainst(equation.Substitute(x, root));
127+
}
128+
129+
/// <summary>
130+
/// Whether <paramref name="substituted"/>, an equation with what was found for its
131+
/// unknowns put in and no symbol left, shows that what was put in is not a solution:
132+
/// it evaluates to a number, and one that is large next to the terms it is the sum of.
133+
/// See <see cref="RelativeResidualTolerance"/> for why the size alone is not enough.
134+
/// </summary>
135+
internal static bool IsEvidenceAgainst(Entity substituted)
136+
{
127137
if (substituted.Evaled is not Number.Complex residual || !residual.IsFinite)
128138
return false;
129139
var size = residual.Abs().EDecimal;
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
using AngouriMath;
9+
using AngouriMath.Extensions;
10+
using System.Linq;
11+
using Xunit;
12+
13+
namespace AngouriMath.Tests.Algebra
14+
{
15+
/// <summary>
16+
/// Square systems where solving one equation widens it, so the elimination finds rows that
17+
/// are no solution: <c>sqrt(y) = x</c> is solved for <c>y</c> as <c>x^2</c>, which holds only
18+
/// where <c>x</c> is not negative. Each was answered with such a row, and the rows are now
19+
/// put back into the system.
20+
/// <a href="https://github.com/asc-community/AngouriMath/issues/2123">#2123</a>
21+
/// </summary>
22+
[Trait("Area", "Algebra")]
23+
public sealed class SpuriousSystemRowTest
24+
{
25+
private static Entity.Matrix? Solve(params string[] equations)
26+
=> MathS.Equations(equations.Select(e => e.ToEntity()).ToArray()).Solve("x", "y");
27+
28+
/// <summary>
29+
/// A row that fails an equation with no symbol left in it is no solution for any value
30+
/// of anything, and is dropped. <c>[-2, 4]</c> leaves <c>sqrt(4) - (-2) = 4</c>, and
31+
/// <c>[-1, -1]</c> leaves <c>ln(-1) + ln(-1) = 2 pi i</c>.
32+
/// </summary>
33+
[Theory]
34+
[InlineData("sqrt(y) - x", "y - 4", "2", "4")]
35+
[InlineData("ln(x) + ln(y)", "x - y", "1", "1")]
36+
public void ARowThatIsNoSolutionIsDropped(string first, string second, string x, string y)
37+
{
38+
var solutions = Solve(first, second);
39+
Assert.NotNull(solutions);
40+
Assert.Equal(1, solutions!.RowCount);
41+
Assert.Equal(Entity.Number.Integer.Create(0), (solutions[0, 0] - x).Simplify());
42+
Assert.Equal(Entity.Number.Integer.Create(0), (solutions[0, 1] - y).Simplify());
43+
}
44+
45+
/// <summary>
46+
/// <c>[-1, 1]</c> was the only row, and <c>sqrt(1) - (-1)</c> is 2: the system has no
47+
/// solution, which <see cref="EquationSystem.Solve"/> answers as <see langword="null"/>.
48+
/// </summary>
49+
[Fact]
50+
public void ASystemWhoseOnlyRowIsNoSolutionHasNone()
51+
=> Assert.Null(Solve("sqrt(y) - x", "x + 1"));
52+
53+
/// <summary>
54+
/// <c>[-sqrt(a), a]</c> fails at <c>a = 137/100</c> and holds at <c>a = 0</c>, so it
55+
/// cannot be dropped as no solution, and the system is declined instead of being
56+
/// answered by the other row alone. A row like it that holds for some values only, as
57+
/// <c>sqrt(t^2) = t</c> does for positive <c>t</c>, would be lost by dropping it.
58+
/// </summary>
59+
[Fact]
60+
public void ARowThatFailsForSomeValueDeclinesTheSystem()
61+
=> Assert.Null(Solve("sqrt(y) - x", "y - a"));
62+
63+
/// <summary>
64+
/// What was answered rightly still is: rows in a symbol of the system's own, and rows in
65+
/// an integer parameter, which are tried with it at a whole number and not at the value
66+
/// the system's own symbols are tried at. Each row is checked here at several values of
67+
/// both, negative ones among them.
68+
/// </summary>
69+
[Theory]
70+
[InlineData("x * y - a", "x - y", 2)]
71+
[InlineData("x ^ 2 - a", "y - x", 2)]
72+
[InlineData("sin(x) - y", "y - 1/2", 2)]
73+
[InlineData("tan(x) - y", "y - 1", 1)]
74+
[InlineData("sqrt(x) + y", "x - 1", 1)]
75+
public void ARowThatHoldsIsKept(string first, string second, int rows)
76+
{
77+
var solutions = Solve(first, second);
78+
Assert.NotNull(solutions);
79+
Assert.Equal(rows, solutions!.RowCount);
80+
foreach (var at in new[] { -1, 0, 2 })
81+
for (var row = 0; row < solutions.RowCount; row++)
82+
foreach (var equation in new[] { first, second })
83+
{
84+
var residual = equation.ToEntity().Substitute("x", solutions[row, 0]).Substitute("y", solutions[row, 1]);
85+
foreach (var symbol in residual.Vars.ToList())
86+
residual = residual.Substitute(symbol, symbol.Name == "a" ? 1.7 + at : at);
87+
var value = Assert.IsAssignableFrom<Entity.Number.Complex>(residual.Evaled);
88+
Assert.True(((Entity.Number.Real)value.Abs()).EDecimal.ToDouble() < 1e-9, $"{equation} at row {row}, {at}: {value}");
89+
}
90+
}
91+
}
92+
}

0 commit comments

Comments
 (0)