Skip to content

Commit 376164d

Browse files
Decline a substitution of x by itself in the multiplicative exponential solver (#2432)
* Decline a substitution of x by itself in the multiplicative exponential solver (#2424) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 131c718 commit 376164d

5 files changed

Lines changed: 176 additions & 8 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,31 @@ one inside another was answered with the empty set, a claim that it has no solut
414414
| `"1/(2 + p^(-3)) = 1/3".Solve("p")` | `{ }` | `{ 1, -1/2 + i * 1/2 * sqrt(3), -1/2 + i * -1/2 * sqrt(3) }` |
415415
| `"1/(1 + x^(-2)) = y".Solve("x")` | `{ }` | `{ ((-1) / (-y) - 1) ^ (-1/2), -((-1) / (-y) - 1) ^ (-1/2) }` |
416416

417+
### An equation with a power of x to a number that is not real is solved rather than overflowing the stack
418+
419+
**A crash becomes an answer.** A power of x to an exponent that is a number but not a real one, such as
420+
`t ^ ln(-2)` (which is how `(-2)^x` reaches the solver), was substituted by x itself. That renamed the
421+
variable, the same equation was asked again, and the stack overflowed and took the process down. The
422+
substitution is declined now, and the equation goes on to the other routes. Where Newton's method answers it, a
423+
point is a root only if the last step was small relative to the point. Without that, points crawling towards
424+
`t = 0`, where every term vanishes, were kept: `x = -12.536 + 2.550i` was answered for `(-2)^x + 4^x = 0`, a
425+
quarter of the way from the nearest root. A point is also not a root where a function in the equation is undefined
426+
at exact arguments: Newton's method compiles `0^i` to 0, so `x^i + x = 0` had 0 among its roots, where `0^i` has no
427+
value. The answers are the roots that lie within the search, not the whole
428+
family `x = (ln(-s) + 2 pi i k) / (ln(a) - ln(b))`
429+
([#2319](https://github.com/asc-community/AngouriMath/issues/2319)).
430+
[#2424](https://github.com/asc-community/AngouriMath/issues/2424)
431+
432+
| Input | Was (2.6.0) | Now |
433+
|---|---|---|
434+
| `"(-2)^x + 4^x = 0".Solve("x")` | stack overflow | nine roots `(2k + 1) pi i / (pi i - ln(2))`, `k` from -7 to 1, in decimals |
435+
| `"(-3)^x + 9^x = 0".Solve("x")` | stack overflow | seven roots `(2k + 1) pi i / (pi i - ln(3))`, `k` from -5 to 1, in decimals |
436+
| `"(-2)^x - 4^x = 0".Solve("x")` | stack overflow | eight roots `2k pi i / (pi i - ln(2))`, `k` from -6 to 1, in decimals |
437+
| `"(-2)^x + 2^x = 0".Solve("x")` | stack overflow | `{ -5, -3, -1, 1, 3 }` |
438+
| `"x^(1 + i) + x = 0".Solve("x")` | stack overflow | `0` and `e^((2k + 1) pi)` for `k` from -3 to 0, in decimals |
439+
| `"x^i + x = 0".Solve("x")` | stack overflow | `{ -e^(pi/2) i, e^(-pi/2) i }`, in decimals |
440+
| `"x^i + x^(2*i) = 0".Solve("x")` | stack overflow | `{ e^pi }`, in decimals |
441+
417442
### A vanishing factor times an infinity is asked as a whole when read as a part
418443

419444
**Silent: a limit with, somewhere inside it, a product of a factor tending to 0 and one tending to an infinity is

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,13 @@ Entity ApplyPowerTransform(Entity @base, Entity arg)
226226

227227
MultithreadingFunctional.ExitIfCancelled();
228228
}
229+
// A substitution of x by itself only renames the variable, and solving the renamed
230+
// equation asks this solver the same question again, without end. It is what is left
231+
// when every exponent is numeric but one is not real, so the case above cannot choose
232+
// a power of x: (-2)^x + 4^x = 0 reaches here as t^ln(-2) + t^ln(4), and so does
233+
// x^(1 + i) + x = 0. https://github.com/asc-community/AngouriMath/issues/2424
234+
if (substitution == x)
235+
return null;
229236
expr = expr.Substitute(substitution, replacement);
230237
if (expr.ContainsNode(x)) return null; // cannot be solved, not a multiplicative exponenial equation
231238

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

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,8 @@ internal static Set UnsolvedWhereIndependenceIsDenied(Set roots, Entity conditio
162162
/// Whether a root demonstrably fails the equation. Anything that cannot be
163163
/// evaluated to a number -- a root still carrying a parameter, say
164164
/// <c>pi + 2 * pi * n_1</c>, or one whose residual is not finite -- is kept, so
165-
/// that a root is only ever dropped on positive evidence against it.
165+
/// that a root is only ever dropped on positive evidence against it. A function
166+
/// undefined at exact arguments is such evidence; see <see cref="IsUndefinedExactly"/>.
166167
/// </summary>
167168
private static bool IsSpurious(Entity equation, Variable x, Entity root)
168169
{
@@ -183,7 +184,32 @@ private static bool IsSpurious(Entity equation, Variable x, Entity root)
183184
return true;
184185
if (root.Vars.Any())
185186
return false;
186-
return IsEvidenceAgainst(equation.Substitute(x, root));
187+
var substituted = equation.Substitute(x, root);
188+
return IsUndefinedExactly(substituted) || IsEvidenceAgainst(substituted);
189+
}
190+
191+
/// <summary>
192+
/// Whether <paramref name="substituted"/>, with no symbol left in it, has no value because
193+
/// some function in it is undefined at its arguments: a node whose arguments are all exact
194+
/// numbers and whose own value is not a finite number. <c>x^i + x</c> at 0 is one, since
195+
/// <c>0^i</c> is undefined, so 0 is not a root of <c>x^i + x = 0</c> however small the
196+
/// compiled function Newton's method iterated on is there.
197+
/// </summary>
198+
/// <remarks>
199+
/// A residual that is not finite is otherwise no evidence against a root: a root found in
200+
/// decimals carries rounding, and a function taken at it next to the edge of its domain, or
201+
/// a term that overflows, may have no value where the root itself gives one. Exact arguments
202+
/// have neither to come from. https://github.com/asc-community/AngouriMath/issues/2424
203+
/// </remarks>
204+
internal static bool IsUndefinedExactly(Entity substituted)
205+
{
206+
static bool IsExact(Entity argument)
207+
=> argument.Evaled is Complex value && value.RealPart is Rational && value.ImaginaryPart is Rational;
208+
foreach (var node in substituted.Nodes)
209+
if (node.DirectChildren.Count > 0 && node.DirectChildren.All(IsExact)
210+
&& node.Evaled is Complex { IsFinite: false })
211+
return true;
212+
return false;
187213
}
188214

189215
/// <summary>

‎Sources/AngouriMath/Functions/Continuous/Solvers/NumericalSolving/NewtonSolver.cs‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,18 @@ static Complex NewtonIter(FastExpression f, FastExpression df, NumericsComplex v
4747
{
4848
var prev = value;
4949

50-
NumericsComplex ChooseGood() =>
51-
NumericsComplex.Abs(prev - value) > (double)MathS.Settings.PrecisionErrorCommon.Value
52-
? double.NaN
53-
: value;
50+
// Converged means the last step was small beside the point, not only small: near a
51+
// zero that every term shares, t ^ ln(-2) + t ^ ln(4) at t = 0, the iteration crawls
52+
// and its steps fall under any fixed tolerance while it is still a fifth of the way
53+
// from where it stops, and those points came back as roots. So below 1 the step is
54+
// measured against the point; from 1 up the tolerance is what it always was.
55+
// https://github.com/asc-community/AngouriMath/issues/2424
56+
NumericsComplex ChooseGood()
57+
{
58+
var tolerance = (double)MathS.Settings.PrecisionErrorCommon.Value;
59+
var scale = Math.Min(1, Math.Max(NumericsComplex.Abs(value), tolerance));
60+
return NumericsComplex.Abs(prev - value) > tolerance * scale ? double.NaN : value;
61+
}
5462

5563
int minCheckIters = (int)Math.Sqrt(precision);
5664
for (int i = 0; i < precision; i++)
@@ -341,11 +349,16 @@ private static Entity WithoutConditions(Entity expr)
341349
/// </summary>
342350
/// <returns>
343351
/// <see langword="true"/> for anything that cannot be checked, so that a root is
344-
/// only ever dropped on positive evidence that it is spurious.
352+
/// only ever dropped on positive evidence that it is spurious. A point where the
353+
/// expression is undefined at exact arguments is such evidence: the compiled form
354+
/// takes <c>0^i</c> to be 0, and <c>x^i + x</c> was answered with the root 0.
345355
/// </returns>
346356
private static bool Satisfies(Entity expr, Entity.Variable v, Complex root)
347357
{
348-
return expr.Substitute(v, root).Evaled is not Complex residual
358+
var substituted = expr.Substitute(v, root);
359+
if (AnalyticalSolving.StatementSolver.IsUndefinedExactly(substituted))
360+
return false;
361+
return substituted.Evaled is not Complex residual
349362
|| !residual.IsFinite
350363
|| residual.Abs().EDecimal.LessThan(MathS.Settings.PrecisionErrorCommon);
351364
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
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 System;
9+
using System.Linq;
10+
using System.Threading.Tasks;
11+
using AngouriMath;
12+
using AngouriMath.Extensions;
13+
using Xunit;
14+
using NumericsComplex = System.Numerics.Complex;
15+
16+
namespace AngouriMath.Tests.Common
17+
{
18+
/// <summary>
19+
/// A power of x to an exponent that is a number but not a real one was substituted by x itself,
20+
/// which renamed the variable and asked the same equation again until the stack overflowed:
21+
/// <c>(-2)^x + 4^x = 0</c> reaches that as <c>t^ln(-2) + t^ln(4)</c>.
22+
/// <a href="https://github.com/asc-community/AngouriMath/issues/2424">#2424</a>
23+
/// </summary>
24+
[Trait("Area", "Common")]
25+
public sealed class ANegativeBaseExponentialSolveTerminatesTest
26+
{
27+
private static readonly TimeSpan Budget = LimitTermination.Guard;
28+
29+
private static Entity.Set Solved(string equation)
30+
{
31+
var task = Task.Run(() => equation.ToEntity().Solve("x"));
32+
Assert.True(task.Wait(Budget), $"{equation} did not finish within {Budget.TotalSeconds}s");
33+
return task.Result;
34+
}
35+
36+
private static NumericsComplex Value(Entity root)
37+
=> Assert.IsAssignableFrom<Entity.Number.Complex>(root.EvalNumerical()).ToNumerics();
38+
39+
/// <summary>
40+
/// <c>a^x + s b^x = 0</c> with <c>s = 1</c> or <c>-1</c>. With principal powers it is
41+
/// <c>e^(x (ln a - ln b)) = -s</c>, so the roots are
42+
/// <c>x = (ln(-s) + 2 pi i k) / (ln a - ln b)</c> for every whole <c>k</c>:
43+
/// <c>(-2)^x + 4^x = 0</c> has <c>x = (2k + 1) pi i / (pi i - ln 2)</c>, the first of which is
44+
/// <c>0.95358 - 0.21039i</c>, and <c>(-2)^x + 2^x = 0</c> has the odd integers. Each root
45+
/// the solver answers is to be one of them; declining is honest, an empty set is not.
46+
/// </summary>
47+
[Theory]
48+
[InlineData("(-2)^x + 4^x = 0", -2, 4, 1)]
49+
[InlineData("(-3)^x + 9^x = 0", -3, 9, 1)]
50+
[InlineData("(-2)^x - 4^x = 0", -2, 4, -1)]
51+
[InlineData("(-2)^x + 2^x = 0", -2, 2, 1)]
52+
public void TheRootsAreOnTheFamily(string equation, int a, int b, int sign)
53+
{
54+
var solved = Solved(equation);
55+
if (solved is not Entity.Set.FiniteSet roots)
56+
return;
57+
Assert.NotEmpty(roots);
58+
var rate = NumericsComplex.Log(a) - NumericsComplex.Log(b);
59+
var shift = NumericsComplex.Log(-sign);
60+
foreach (var root in roots)
61+
{
62+
var x = Value(root);
63+
var left = NumericsComplex.Exp(x * NumericsComplex.Log(a));
64+
var right = sign * NumericsComplex.Exp(x * NumericsComplex.Log(b));
65+
Assert.True(NumericsComplex.Abs(left + right) <= 1e-9 * (NumericsComplex.Abs(left) + NumericsComplex.Abs(right)),
66+
$"{root} leaves {left + right} in {equation}");
67+
var k = (x * rate - shift) / (2 * Math.PI * NumericsComplex.ImaginaryOne);
68+
Assert.True(Math.Abs(k.Real - Math.Round(k.Real)) < 1e-9 && Math.Abs(k.Imaginary) < 1e-9,
69+
$"{root} is not on the family of {equation}: k = {k}");
70+
}
71+
}
72+
73+
/// <summary>
74+
/// The same substitution without a negative base. <c>x^(1 + i) + x</c> is
75+
/// <c>x (x^i + 1)</c>, whose roots are 0, where <c>0^(1 + i)</c> is 0, and <c>e^((2k + 1) pi)</c>.
76+
/// <c>x^i + x</c> and <c>x^i + x^(2i)</c> have no root at 0, where <c>0^i</c> is undefined,
77+
/// though the function Newton's method compiles is 0 there.
78+
/// </summary>
79+
[Theory]
80+
[InlineData("x^(1 + i) + x")]
81+
[InlineData("x^i + x")]
82+
[InlineData("x^i + x^(2*i)")]
83+
public void AComplexExponentOfXTerminates(string expression)
84+
{
85+
if (Solved(expression + " = 0") is not Entity.Set.FiniteSet roots)
86+
return;
87+
Assert.NotEmpty(roots);
88+
foreach (var root in roots)
89+
{
90+
var residual = expression.ToEntity().Substitute("x", root).EvalNumerical();
91+
var value = Assert.IsAssignableFrom<Entity.Number.Complex>(residual);
92+
Assert.True(value.IsFinite && NumericsComplex.Abs(value.ToNumerics()) <= 1e-9 * Math.Max(1, NumericsComplex.Abs(Value(root))),
93+
$"{root} leaves {residual} in {expression} = 0");
94+
}
95+
}
96+
}
97+
}

0 commit comments

Comments
 (0)