Skip to content

Commit 429f5f6

Browse files
A system with more or fewer equations than unknowns is solved or declined (#2124)
EquationSystem.Solve threw WrongNumberOfArgumentsException for a non-square system unless the triangularisation took it (polynomial over Q, rational solutions) or it was short and linear with rational coefficients. The exception says the call was wrong, and it was not: x^2 + y^2 = 1 for x and y has a family of solutions, and sin(x) = 0 with x = 0 has one. Happypig375 agreed on #212 that accepting new forms and not throwing is fine. Such a system now goes to NonSquareSystemSolver. It eliminates the last unknown from the equation with the fewest occurrences of it, recurses on each root, and makes an unknown that nothing is left to constrain a parameter, t_1, as the linear path does. With no unknown left, an equation that is a number away from zero drops its branch; one that cannot be decided, like (a + b)/2 - c, makes that equation's roots no answer, and the next equation is tried. Every family is substituted back into every equation and kept only where each one vanishes, and a system with one that does not is declined as null, which Solve documents as no solution found. Two cases need that check: - sqrt(y) = x is solved for y as x^2, which is no solution for a negative x; sqrt(t^2) - t does not simplify to 0, so the system is declined rather than answered (t, t^2). - A coefficient that is zero without being written so: t^2 - c (t^2/c) simplifies to 0 provided not c = 0 for c = (a + 1)^2 - a^2 - 2a - 1. A provided condition counts only where it holds with the symbols pinned, so that family is declined too. A square system does not reach this, so no square answer changes. Measured, each non-square shape probed on 2.6.0 and on this branch: x^2 + y^2 - 1 in x, y exception -> [[t_1, sqrt(-(t_1 ^ 2 + -1))], [t_1, -sqrt(-(t_1 ^ 2 + -1))]] a*x + y - 1 in x, y exception -> [[t_1, -(a * t_1 + -1)]] sin(x); x in x exception -> [0] sin(x) - y; cos(x) - y; x - pi/4 exception -> [[pi / 4, 1/2 * sqrt(2)]] sqrt(y) - x in x, y exception -> null x + y - a; x - y - b; x - c in x, y exception -> null Part of #212 Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 24ae82f commit 429f5f6

8 files changed

Lines changed: 382 additions & 24 deletions

File tree

‎BREAKING-CHANGES.md‎

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

4343
## Unreleased — since 2.6.0
4444

45+
### A system with more or fewer equations than unknowns is solved or declined
46+
47+
**Not silent: what was an exception is an answer or `null`.** `EquationSystem.Solve` threw
48+
`WrongNumberOfArgumentsException` for a system with more or fewer equations than unknowns, unless it was polynomial
49+
over the rationals with rational solutions or had fewer equations and was linear with rational coefficients. Such a
50+
system is now eliminated one unknown at a time, and an unknown that nothing is left to constrain becomes a parameter,
51+
`t_1`, as in the linear case. Every row is substituted back into every equation and kept only where each simplifies to
52+
zero. Where one does not, or where a branch cannot be decided, the system is declined as `null`, which `Solve`
53+
documents as no solution found ([#212](https://github.com/asc-community/AngouriMath/issues/212)). Code that caught the
54+
exception around `Solve` to detect a non-square system no longer sees it.
55+
56+
| Input | Was (2.6.0) | Now |
57+
|---|---|---|
58+
| `MathS.Equations("x^2 + y^2 - 1").Solve("x", "y")` | `WrongNumberOfArgumentsException` | `[[t_1, sqrt(-(t_1 ^ 2 + -1))], [t_1, -sqrt(-(t_1 ^ 2 + -1))]]` |
59+
| `MathS.Equations("a*x + y - 1").Solve("x", "y")` | `WrongNumberOfArgumentsException` | `[[t_1, -(a * t_1 + -1)]]` |
60+
| `MathS.Equations("sin(x)", "x").Solve("x")` | `WrongNumberOfArgumentsException` | `[0]` |
61+
| `MathS.Equations("sin(x) - y", "cos(x) - y", "x - pi/4").Solve("x", "y")` | `WrongNumberOfArgumentsException` | `[[pi / 4, 1/2 * sqrt(2)]]` |
62+
| `MathS.Equations("sqrt(y) - x").Solve("x", "y")` | `WrongNumberOfArgumentsException` | `null`: `y = x^2` is no solution where `x` is negative |
63+
| `MathS.Equations("x + y - a", "x - y - b", "x - c").Solve("x", "y")` | `WrongNumberOfArgumentsException` | `null`: there are solutions only where `a + b = 2c` |
64+
4565
### `am_classify` is a preliminary tool, served by `amcli mcp --preliminary`
4666

4767
**Not silent: what answered is a failure naming the flag.** `am_classify` guesses which field a formula comes from by

‎Sources/.editorconfig‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,9 +252,15 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
252252
[AngouriMath/Functions/Continuous/Solvers/EquationSolver/LinearSystemSolver.cs]
253253
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
254254

255+
[AngouriMath/Functions/Continuous/Solvers/EquationSolver/NonSquareSystemSolver.cs]
256+
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
257+
255258
[AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs]
256259
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
257260

261+
[Tests/UnitTests/Algebra/SolveTest/NonSquareSystemTest.cs]
262+
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
263+
258264
[Tests/UnitTests/Algebra/SolveTest/ParametricSystemTest.cs]
259265
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
260266

‎Sources/AngouriMath/Core/EquationSystem.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,10 @@ private static Entity AsAnExpressionEqualToZero(Entity equation)
6767
/// Solves a system of equations, if possible.
6868
/// </summary>
6969
/// <param name="vars">
70-
/// The umber of variables must match number of equations
70+
/// The unknowns, as many as there are equations or not. Where there are more, or where a
71+
/// system leaves one free, it becomes a parameter in the answer: <c>x^2 + y^2 = 1</c> for
72+
/// <c>x</c> and <c>y</c> is two rows, <c>x = t_1</c> with <c>y</c> the positive and the
73+
/// negative square root of <c>1 - t_1^2</c>.
7174
/// </param>
7275
/// <return>
7376
/// If there exists at least one solution, returns a solution matrix

‎Sources/AngouriMath/Docs/Usage/Exceptions.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,9 @@ largest base there are digits for, and the base that was asked for.
216216
### `WrongNumberOfArgumentsException`
217217

218218
An API call whose arity does not match: a compiled function called with the wrong number of values,
219-
a truth table asked for over a different number of variables than the expression has, a system of
220-
equations with more or fewer equations than unknowns. Where the expression is in scope the message
221-
names it and its variables.
219+
or a truth table asked for over a different number of variables than the expression has. Where the
220+
expression is in scope the message names it and its variables. A system of equations with more or
221+
fewer equations than unknowns is not one: it is solved, or declined as `null`.
222222

223223
Compare `FunctionArgumentCountException`, which is the same complaint about a function call written
224224
inside a string. **Use `FunctionArgumentCountException` from the parser and this one from

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ internal static Set Solve(Entity equation, Variable x)
127127
if (Groebner.GroebnerSystemSolver.TrySolve(equations, variables, out var triangularised))
128128
return triangularised;
129129

130-
// Fewer equations than unknowns is not a mistake by the caller, which is what
131-
// the exception below says it is. A linear system of that shape has infinitely
130+
// Fewer equations than unknowns is not a mistake by the caller, which is what an
131+
// exception here used to say it was. A linear system of that shape has infinitely
132132
// many solutions and one family that describes them all, so it is answered as
133133
// that family -- the unknowns a row reduction leaves free become parameters.
134134
// Only the short count is taken here: a square system that is rank-deficient
@@ -139,8 +139,14 @@ internal static Set Solve(Entity equation, Variable x)
139139
equations, variables, out var family))
140140
return family;
141141

142+
// Nor is any other count: `x^2 + y^2 = 1` has a family of solutions in a
143+
// parameter, and `sin(x) = 0` with `x = 0` has one solution. Those are eliminated,
144+
// and a system whose answer cannot be shown to hold is declined, as `Solve`
145+
// documents. https://github.com/asc-community/AngouriMath/issues/212
142146
if (equations.Count != vars.Length)
143-
throw new WrongNumberOfArgumentsException("Number of equations must be equal to that of vars");
147+
return NonSquareSystemSolver.Solve(equations, variables, ledger) is { } families
148+
? new MatrixBuilder(families, vars.Length).ToMatrix()
149+
: null;
144150
int initVarCount = vars.Length;
145151

146152
var res = InSolveSystem(equations, vars, Sumf.Sum(equations), ledger);
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
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.Core.Budgets;
9+
using AngouriMath.Core.Exceptions;
10+
using System;
11+
using static AngouriMath.Entity;
12+
using static AngouriMath.Entity.Number;
13+
using static AngouriMath.Entity.Set;
14+
15+
namespace AngouriMath.Functions.Algebra.AnalyticalSolving
16+
{
17+
/// <summary>
18+
/// A system with more or fewer equations than unknowns that neither the triangularisation nor
19+
/// <see cref="LinearSystemSolver"/> takes, such as <c>x^2 + y^2 = 1</c> for <c>x</c> and
20+
/// <c>y</c>, or <c>sin(x) = 0</c> and <c>x = 0</c> for <c>x</c>. Each unknown is eliminated in
21+
/// turn, an unknown that nothing is left to constrain becomes a parameter, and every family
22+
/// found is substituted back into every equation.
23+
/// <a href="https://github.com/asc-community/AngouriMath/issues/212">#212</a>
24+
/// </summary>
25+
/// <remarks>
26+
/// <para>
27+
/// <b>An answer is given only where it is shown to hold.</b> The elimination trusts each solve
28+
/// it makes, and a solve can answer for a case its equation does not cover: <c>sqrt(y) = x</c>
29+
/// is solved for <c>y</c> as <c>x^2</c>, which is no solution where <c>x</c> is negative. So
30+
/// each family is kept only where every equation, with the family substituted, simplifies to
31+
/// <c>0</c>. <c>sqrt(t^2) - t</c> does not, and that system is declined.
32+
/// </para>
33+
/// <para>
34+
/// <b>A decline declines the whole system.</b> An equation left with no unknown in it is zero,
35+
/// a number away from zero, or neither as far as can be told, like <c>(a + b)/2 - c</c>. A
36+
/// branch where one is away from zero has no solutions and is dropped. A branch where one
37+
/// cannot be told gives no answer for the system, rather than leaving the other branches to
38+
/// read as all of its solutions.
39+
/// </para>
40+
/// <para>
41+
/// A square system does not come here. It is the eliminator's in
42+
/// <see cref="EquationSolver.InSolveSystem"/>, whose answers this would change.
43+
/// </para>
44+
/// </remarks>
45+
internal static class NonSquareSystemSolver
46+
{
47+
/// <summary>
48+
/// The solutions of <paramref name="equations"/> in <paramref name="variables"/>, a list of
49+
/// values in their order for each family, or <see langword="null"/> where none were found.
50+
/// </summary>
51+
internal static List<List<Entity>>? Solve(List<Entity> equations, Variable[] variables, BudgetLedger ledger)
52+
{
53+
// One parameter per unknown that is left free, the same in every branch. Each is
54+
// minted against the equations and the parameters already minted, since CreateUnique
55+
// compares whole names in use and would otherwise hand back the same name twice.
56+
var parameters = new Variable?[variables.Length];
57+
Entity nameSource = equations.Count > 0 ? Sumf.Sum(equations) : Integer.Zero;
58+
Variable ParameterFor(int index)
59+
{
60+
if (parameters[index] is { } minted)
61+
return minted;
62+
var parameter = Variable.CreateUnique(nameSource, "t");
63+
nameSource += parameter;
64+
return parameters[index] = parameter;
65+
}
66+
67+
if (Eliminate(equations, variables, variables.Length, ParameterFor, ledger) is not { Count: > 0 } families)
68+
return null;
69+
foreach (var family in families)
70+
foreach (var equation in equations)
71+
{
72+
var substituted = equation;
73+
for (var index = 0; index < variables.Length; index++)
74+
substituted = substituted.Substitute(variables[index], family[index]);
75+
if (!Vanishes(substituted))
76+
return null;
77+
}
78+
return families;
79+
}
80+
81+
/// <summary>
82+
/// The solutions in the first <paramref name="count"/> of <paramref name="variables"/>, each
83+
/// a list of their values in order. Empty where there are none, and
84+
/// <see langword="null"/> where that could not be told.
85+
/// </summary>
86+
private static List<List<Entity>>? Eliminate(List<Entity> equations, Variable[] variables, int count,
87+
Func<int, Variable> parameterFor, BudgetLedger ledger)
88+
{
89+
// Charged as InSolveSystem charges it: one unit for each candidate explored.
90+
if (!ledger.Spend())
91+
throw new NotSufficientlySupportedException(
92+
"this system of equations is not solvable within the budget. Raise "
93+
+ "MathS.Settings.Budget to allow more, or pass a cancellation token with "
94+
+ "MathS.Multithreading.SetLocalCancellationToken");
95+
96+
// No unknown is left, so each equation holds as it stands or does not.
97+
if (count == 0)
98+
{
99+
var told = true;
100+
foreach (var equation in equations)
101+
switch (Holds(equation))
102+
{
103+
case false:
104+
return new();
105+
case null:
106+
told = false;
107+
break;
108+
}
109+
return told ? new() { new() } : null;
110+
}
111+
112+
// No equation is left, so every unknown left is free.
113+
if (equations.Count == 0)
114+
{
115+
var free = new List<Entity>();
116+
for (var index = 0; index < count; index++)
117+
free.Add(parameterFor(index));
118+
return new() { free };
119+
}
120+
121+
var variable = variables[count - 1];
122+
// The equation with the fewest occurrences of the unknown first, which is solved by
123+
// inverting it and has the plainest roots: of `cos(x) = sin(x)` and `x = pi/4`, the
124+
// first is solved as ln(sqrt(i))/i and the second as pi/4.
125+
var candidates = Enumerable.Range(0, equations.Count)
126+
.Where(i => equations[i].ContainsNode(variable))
127+
.OrderBy(i => equations[i].Nodes.Count(node => node == variable))
128+
.ThenBy(i => equations[i].Complexity)
129+
.ToList();
130+
foreach (var i in candidates)
131+
{
132+
// An empty set is passed over as InSolveSystem passes it over: substituting an
133+
// earlier unknown can leave an occurrence that cancels, and then the solve has
134+
// nothing to say about this one.
135+
if (equations[i].SolveEquation(variable).InnerSimplified is not FiniteSet roots || roots.Count == 0)
136+
continue;
137+
var rest = new List<Entity>(equations);
138+
rest.RemoveAt(i);
139+
if (EachRoot(roots, rest, variables, count, parameterFor, ledger) is { } solutions)
140+
return solutions;
141+
// This equation's roots left a question that could not be told. Another
142+
// equation's may not: `sin(x) = 0` gives x = 2 pi n_1, where `x = 0` gives 0.
143+
}
144+
145+
if (candidates.Count > 0)
146+
return null;
147+
// Nothing constrains this unknown, so it is a parameter in every solution of the rest.
148+
var others = Eliminate(equations, variables, count - 1, parameterFor, ledger);
149+
others?.ForEach(family => family.Add(parameterFor(count - 1)));
150+
return others;
151+
}
152+
153+
/// <summary>
154+
/// The solutions where the last of the unknowns is each of <paramref name="roots"/> in
155+
/// turn, or <see langword="null"/> where that could not be told for one of them.
156+
/// </summary>
157+
private static List<List<Entity>>? EachRoot(FiniteSet roots, List<Entity> rest, Variable[] variables, int count,
158+
Func<int, Variable> parameterFor, BudgetLedger ledger)
159+
{
160+
var variable = variables[count - 1];
161+
var solutions = new List<List<Entity>>();
162+
foreach (var root in roots)
163+
{
164+
var substituted = rest.Select(equation => equation.Substitute(variable, root)).ToList();
165+
if (Eliminate(substituted, variables, count - 1, parameterFor, ledger) is not { } families)
166+
return null;
167+
foreach (var family in families)
168+
{
169+
var value = root;
170+
for (var index = 0; index < count - 1; index++)
171+
value = value.Substitute(variables[index], family[index]);
172+
family.Add(value.InnerSimplified);
173+
solutions.Add(family);
174+
}
175+
}
176+
return solutions;
177+
}
178+
179+
/// <summary>
180+
/// Whether <paramref name="equation"/>, with no unknown left in it, holds:
181+
/// <see langword="true"/> where it simplifies to zero, <see langword="false"/> where it is a
182+
/// number away from zero, and <see langword="null"/> where neither can be told.
183+
/// </summary>
184+
private static bool? Holds(Entity equation)
185+
{
186+
if (Vanishes(equation))
187+
return true;
188+
if (equation.Vars.Any() || equation.Evaled is not Complex value || value.IsNaN)
189+
return null;
190+
// An exact number that is not zero is not zero. A decimal is taken as away from zero
191+
// only well past the digits its evaluation may have lost.
192+
if (value is Rational)
193+
return false;
194+
return ((Real)value.Abs()).EDecimal.ToDouble() > 1e-9 ? false : null;
195+
}
196+
197+
/// <summary>
198+
/// Whether <paramref name="expression"/> is zero for every value of its symbols: zero as it
199+
/// is evaluated, or simplified to zero. A simplification to <c>0 provided C</c> counts only
200+
/// where <c>C</c> holds with the symbols pinned, since <c>t - c (t/c)</c> simplifies to
201+
/// <c>0 provided not c = 0</c> for a <c>c</c> that is zero without being written
202+
/// <c>0</c>, such as <c>(a + 1)^2 - a^2 - 2a - 1</c>.
203+
/// </summary>
204+
private static bool Vanishes(Entity expression)
205+
{
206+
if (expression.InnerSimplified.Evaled is Complex { IsZero: true })
207+
return true;
208+
// Away from zero at a point is not zero everywhere, which settles most without
209+
// simplifying.
210+
if (Pinned(expression).Evaled is Complex { IsNaN: false } atAPoint
211+
&& ((Real)atAPoint.Abs()).EDecimal.ToDouble() > 1e-9)
212+
return false;
213+
return expression.Simplify() switch
214+
{
215+
Providedf(var simplified, var condition) =>
216+
simplified.Evaled is Complex { IsZero: true } && Pinned(condition).Evaled is Entity.Boolean { Value: true },
217+
var simplified => simplified.Evaled is Complex { IsZero: true },
218+
};
219+
}
220+
221+
/// <summary><paramref name="expression"/> with each of its symbols at a fixed value.</summary>
222+
private static Entity Pinned(Entity expression)
223+
{
224+
var values = new[] { 1.37, 0.61, 2.23, 1.91, 0.83, 1.13 };
225+
var index = 0;
226+
foreach (var symbol in expression.Vars.ToList())
227+
expression = expression.Substitute(symbol, values[index++ % values.Length]);
228+
return expression;
229+
}
230+
}
231+
}

0 commit comments

Comments
 (0)