Skip to content

Commit a46448e

Browse files
Find a polynomial's numerical roots whatever their size (#2516)
Durand-Kerner started its approximations on Cauchy's circle, 1 + max |a_i|, which is never below 1, and settled them to an absolute tolerance. Eight roots near 1e-12 started 1e12 times too far out and did not settle in a thousand sweeps; roots near 1e-30 made the products the step divides by pass below the decimal context's exponent range, every root came out NaN, and NaN compared as settled. The iteration now runs on p(10^e w), with 10^e the power of ten below Fujiwara's bound read off the coefficients' logarithms, so it meets roots of about unit size, and each root is scaled back exactly. A polynomial whose roots are of unit size is solved as before. A root is made with no scale of cancellation: made at the unit scale, a part below half the working digits was rounded onto 0, so x^5 - 3e-60 x + 1e-150 had 0 among its roots. And the Groebner back-substitution read a decimal root that leaves an equation a nonzero rational as extending to no solution. Where the decimals had flushed every power of the root to 0 and left the exact constant term, that was wrong, and the system for the parts of x in (1 + i) + 2x - 3x^2 + x|3 - x| = 0 with x written as 10^30 x was answered { } once the octic under it was solved. Such a root is checked exactly, and the system declined where it holds. Generated equations with x written as 10^12 x: cxcheck went from 25 answers differing to 4, radcheck's powers from 16 to 0, logcheck and radcheck from 2 to 0; the 4 left are unsolved, not wrong. The unscaled cross-checks and the multiplicative scale check are unchanged. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 90db9db commit a46448e

4 files changed

Lines changed: 290 additions & 3 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,22 @@ equation with no terms to cancel, such as one function's value.
5757
| `"(x * (2 - 4x + 2x^2)^(1/3) - 2) * 10^(-12) = 0".ToEntity().Solve("x")` | five roots, two of which leave 3.46e-12 | the three of `x * (2 - 4x + 2x^2)^(1/3) = 2` |
5858
| `"(sin(x) - x) * 10^12 = 0".ToEntity().Solve("x")` | `{ 0 }` | the nine of `sin(x) = x` |
5959

60+
### A polynomial's numerical roots are found whatever their size
61+
62+
**Silent: answers gain roots that were missing, and lose numbers that were not roots.** A polynomial whose roots
63+
have no closed form is solved numerically, and the iteration started on a circle of radius at least 1 and
64+
settled to an absolute tolerance. Roots near `10^-12` were not settled, and the answer was what a search found;
65+
roots near `10^-30` came out as NaN. A root far below the others in size was then rounded onto `0`. The iteration
66+
now runs on the roots scaled to about unit size. And a system solved for the real and imaginary parts of `x`
67+
no longer reads a root whose decimals were flushed to `0` as extending to no solution.
68+
69+
| Input | Was (2.8.0) | Now |
70+
|---|---|---|
71+
| `"x^8 - 7/4*10^(-12)*x^7 - 137/216*10^(-24)*x^6 + 869/432*10^(-36)*x^5 - 12377/23328*10^(-48)*x^4 - 2557/15552*10^(-60)*x^3 - 6815/93312*10^(-72)*x^2 + 961/23328*10^(-84)*x + 961/93312*10^(-96) = 0".ToEntity().Solve("x")` | `{ -1.87e-13 }`, one root of eight | its eight roots, from `-1.06e-12` to `1.45e-12` |
72+
| `"x^5 - 3*10^(-120)*x + 10^(-150) = 0".ToEntity().Solve("x")` | five numbers near `4.7e-24`, none of them a root | its five roots, `10^-30` times those of `x^5 - 3x + 1` |
73+
| `"x^5 - 3*10^(-60)*x + 10^(-150) = 0".ToEntity().Solve("x")` | `0` among the roots, where the polynomial is `10^-150` | `3.33e-91` in its place |
74+
| `"(1 + i) + 2*(10^12*x) - 3*(10^12*x)^2 + 10^12*x*abs(3 - 10^12*x) = 0".ToEntity().Solve("x")` | `{ -1.87e-13 - 1.58e-13i }`, one root of two | both, `10^-12` times those of the equation in `x` |
75+
6076
### `MathS.Parse` and `Entity.TryParse` return a refused call rather than throw it
6177

6278
**Not silent: what threw now returns.** `MathS.Parse` is the parser that does not throw, and `Entity.TryParse` the

‎Sources/AngouriMath/Functions/Algebra/Groebner/GroebnerSystemSolver.cs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,14 @@ static bool BackSubstitute(
209209
if (substituted.Vars.Any())
210210
narrowed.Add(substituted);
211211
else if (substituted is Number.Rational { IsZero: false })
212+
{
213+
// Unless what is left is only the part the decimals did not flush to 0, where
214+
// the root is not shown to extend to nothing, and the equations narrowed by
215+
// the flushed decimals are not to be trusted either.
216+
if (VanishesAtTheExactRoot(equation, variable, root))
217+
return budget.Allow(false, "a root past the decimal range");
212218
consistent = false;
219+
}
213220
}
214221
// A root that leaves an equation a nonzero number extends to no solution.
215222
if (!consistent)
@@ -220,6 +227,48 @@ static bool BackSubstitute(
220227
return true;
221228
}
222229

230+
/// <summary>
231+
/// Whether <paramref name="root"/>, a number in decimals, makes <paramref name="equation"/>
232+
/// in <paramref name="variable"/> alone negligible next to the largest of its terms when
233+
/// the decimals are read as the exact rationals they are.
234+
/// </summary>
235+
/// <remarks>
236+
/// A decimal below about <c>10^-200</c> is flushed to 0 by the decimal context, where a
237+
/// rational is kept exactly. So a root near <c>10^-30</c> put into an eighth-degree
238+
/// polynomial left the polynomial's rational constant term alone, every power of the root
239+
/// gone, and each of the eight roots was read as extending to no solution: the system
240+
/// solved for the parts of x in <c>(1 + i) + 2x - 3x^2 + x|3 - x| = 0</c> with x written as
241+
/// <c>10^30 x</c> was answered <c>{ }</c>. Exactly, the root leaves a residual of the
242+
/// size its hundred digits allow.
243+
/// </remarks>
244+
static bool VanishesAtTheExactRoot(Entity equation, Variable variable, Entity root)
245+
{
246+
if (!root.Nodes.Any(IsADecimal) || root.Evaled is not Number.Complex value
247+
|| !value.RealPart.EDecimal.IsFinite || !value.ImaginaryPart.EDecimal.IsFinite
248+
|| MultivariatePolynomial.TryParse(equation, new Dictionary<Variable, int> { [variable] = 0 }) is not { } polynomial)
249+
return false;
250+
var (re, im) = (ERational.FromEDecimal(value.RealPart.EDecimal), ERational.FromEDecimal(value.ImaginaryPart.EDecimal));
251+
// Each term c z^k exactly, with z^k built up a power at a time.
252+
var powers = new List<(ERational Re, ERational Im)> { (ERational.One, ERational.Zero) };
253+
var (sumRe, sumIm) = (ERational.Zero, ERational.Zero);
254+
var largest = ERational.Zero;
255+
foreach (var term in polynomial.Terms)
256+
{
257+
var power = MultivariatePolynomial.PowerOf(term.Key, 0);
258+
while (powers.Count <= power)
259+
{
260+
var (pRe, pIm) = powers[powers.Count - 1];
261+
powers.Add((pRe.Multiply(re).Subtract(pIm.Multiply(im)), pRe.Multiply(im).Add(pIm.Multiply(re))));
262+
}
263+
var (tRe, tIm) = (powers[power].Re.Multiply(term.Value), powers[power].Im.Multiply(term.Value));
264+
(sumRe, sumIm) = (sumRe.Add(tRe), sumIm.Add(tIm));
265+
var size = tRe.Abs().Add(tIm.Abs());
266+
if (size.CompareTo(largest) > 0)
267+
largest = size;
268+
}
269+
return sumRe.Abs().Add(sumIm.Abs()).CompareTo(largest.Multiply(ERational.FromEDecimal(NegligibleShare))) <= 0;
270+
}
271+
223272
/// <summary>
224273
/// <paramref name="substituted"/> as a polynomial over <c>Q</c> in the variables still to
225274
/// be assigned, where it is one, so that a term the root has made worth nothing is gone.

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

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,10 +110,83 @@ internal static class DurandKerner
110110
/// <summary>
111111
/// The roots of the polynomial with real <paramref name="coefficients"/>, lowest power first,
112112
/// at the precision of <paramref name="context"/>, each approximation at least
113-
/// <c>10^-separationDigits</c> from the others; <see langword="null"/> where they are not
114-
/// settled or not that far apart.
113+
/// <c>10^-separationDigits</c> of the size of the roots from the others;
114+
/// <see langword="null"/> where they are not settled or not that far apart.
115115
/// </summary>
116+
/// <remarks>
117+
/// Solved for <c>w = z / 10^e</c>, with <c>10^e</c> the size of the roots, so that the
118+
/// iteration below meets roots of about unit size whatever theirs is. Its starting circle,
119+
/// the tolerance it settles to and the separation it holds the roots to are in absolute
120+
/// terms, and a polynomial whose roots were all within <c>10^-12</c> of zero was started
121+
/// <c>10^12</c> times as far out as they are and did not settle; with roots within
122+
/// <c>10^-30</c>, the products the step divides by passed below the context's exponent
123+
/// range and every root came out NaN. The system solved for the parts of x in
124+
/// <c>(1 + i) + 2x - 3x^2 + x|3 - x| = 0</c> with x written as <c>10^12 x</c> kept one root
125+
/// of its two. The scaling is by a power of ten, which is exact.
126+
/// </remarks>
116127
private static IReadOnlyList<Complex>? Roots(EDecimal[] coefficients, EContext context, int separationDigits)
128+
{
129+
var exponent = ExponentOfTheRoots(coefficients);
130+
if (exponent == 0)
131+
return RootsOfUnitSize(coefficients, context, separationDigits);
132+
// p(10^e w) has the coefficients c_k 10^(e k).
133+
var scaled = new EDecimal[coefficients.Length];
134+
for (var k = 0; k < scaled.Length; k++)
135+
scaled[k] = coefficients[k].ScaleByPowerOfTen(EInteger.FromInt64(exponent * k));
136+
if (RootsOfUnitSize(scaled, context, separationDigits) is not { } roots)
137+
return null;
138+
var power = EInteger.FromInt64(exponent);
139+
var back = new List<Complex>(roots.Count);
140+
foreach (var root in roots)
141+
back.Add(AsARoot(
142+
root.RealPart.EDecimal.ScaleByPowerOfTen(power).RoundToPrecision(context),
143+
root.ImaginaryPart.EDecimal.ScaleByPowerOfTen(power).RoundToPrecision(context)));
144+
return back;
145+
}
146+
147+
/// <summary>A root with these parts, neither of them read as a residual of cancellation.</summary>
148+
/// <remarks>
149+
/// A root is a value the iteration has settled to the working precision of its own size,
150+
/// not what is left of a difference. Made at the unit scale, a number smaller than half the
151+
/// working digits is taken for such a residual and rounded onto 0: the root 3.3e-91 of
152+
/// <c>x^5 - 3e-60 x + 1e-150</c>, beside four of size 1.3e-15, came out 0, where the
153+
/// polynomial is 1e-150, and 0 was answered as a root. An imaginary part too small to be one
154+
/// is already 0.
155+
/// </remarks>
156+
private static Complex AsARoot(EDecimal real, EDecimal imaginary)
157+
=> Complex.CreateAtScales(real, imaginary, EDecimal.Zero, EDecimal.Zero);
158+
159+
/// <summary>
160+
/// The power of ten nearest below Fujiwara's bound on the roots of the polynomial with
161+
/// <paramref name="coefficients"/>, <c>2 max_k |a_(n-k) / a_n|^(1/k)</c> with <c>a_0</c>
162+
/// halved, read off the coefficients' decimal logarithms so that no quotient of them is
163+
/// formed; 0 where the polynomial has only its leading term.
164+
/// </summary>
165+
private static long ExponentOfTheRoots(EDecimal[] coefficients)
166+
{
167+
var degree = coefficients.Length - 1;
168+
var lead = Log10OfModulus(coefficients[degree]);
169+
var largest = double.NegativeInfinity;
170+
for (var k = 1; k <= degree; k++)
171+
{
172+
var coefficient = coefficients[degree - k];
173+
if (coefficient.IsZero)
174+
continue;
175+
var log = Log10OfModulus(coefficient) - lead - (k == degree ? Math.Log10(2) : 0);
176+
largest = Math.Max(largest, log / k);
177+
}
178+
return double.IsNegativeInfinity(largest) ? 0 : (long)Math.Floor(largest + Math.Log10(2));
179+
}
180+
181+
/// <summary>The decimal logarithm of <c>|value|</c>, to about a double's precision, for any exponent.</summary>
182+
private static double Log10OfModulus(EDecimal value)
183+
{
184+
var rounded = value.Abs().RoundToPrecision(EContext.ForPrecision(17));
185+
return Math.Log10(EDecimal.FromEInteger(rounded.Mantissa).ToDouble()) + EDecimal.FromEInteger(rounded.Exponent).ToDouble();
186+
}
187+
188+
/// <summary><see cref="Roots(EDecimal[], EContext, int)"/>, for roots of about unit size.</summary>
189+
private static IReadOnlyList<Complex>? RootsOfUnitSize(EDecimal[] coefficients, EContext context, int separationDigits)
117190
{
118191
var degree = coefficients.Length - 1;
119192
var digits = context.Precision.ToInt32Checked();
@@ -164,6 +237,9 @@ internal static class DurandKerner
164237
im[i] = im[i].Subtract(stepIm, work);
165238
largest = EDecimal.Max(largest, stepRe.Abs().Add(stepIm.Abs(), work));
166239
}
240+
// A step that is not a number has not settled, and NaN compares as anything.
241+
if (!largest.IsFinite)
242+
return null;
167243
settled = largest.CompareTo(tolerance) <= 0;
168244
}
169245
if (!settled)
@@ -180,7 +256,7 @@ internal static class DurandKerner
180256
for (var i = 0; i < degree; i++)
181257
{
182258
var imaginary = im[i].Abs().CompareTo(half) < 0 ? EDecimal.Zero : im[i].RoundToPrecision(context);
183-
roots.Add(Complex.Create(re[i].RoundToPrecision(context), imaginary));
259+
roots.Add(AsARoot(re[i].RoundToPrecision(context), imaginary));
184260
}
185261
return roots;
186262
}
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
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.Linq;
9+
using System.Numerics;
10+
using AngouriMath.Extensions;
11+
using Xunit;
12+
using static AngouriMath.Entity;
13+
using static AngouriMath.Entity.Set;
14+
15+
namespace AngouriMath.Tests.Algebra
16+
{
17+
/// <summary>
18+
/// A polynomial whose roots have no closed form is solved by the Durand-Kerner iteration,
19+
/// which started its approximations on a circle of radius at least 1 and settled them to an
20+
/// absolute tolerance. So a polynomial with every root near <c>10^-12</c> did not settle, and
21+
/// one with every root near <c>10^-30</c> settled on NaN, its steps having divided by numbers
22+
/// below the decimal range. The iteration now runs on the roots scaled to about unit size.
23+
/// Found by solving generated equations with <c>x</c> written as <c>10^12 x</c>; no issue
24+
/// was filed.
25+
/// </summary>
26+
[Trait("Area", "Algebra")]
27+
public sealed class RootsOfAnySizeAreFoundNumericallyTest
28+
{
29+
/// <summary>The coefficients of an octic whose eight roots are near 1, highest power first.</summary>
30+
private static readonly (int Numerator, int Denominator)[] Octic =
31+
{
32+
(1, 1), (-7, 4), (-137, 216), (869, 432), (-12377, 23328),
33+
(-2557, 15552), (-6815, 93312), (961, 23328), (961, 93312),
34+
};
35+
36+
/// <summary>The coefficients of <c>x^5 - 3x + 1</c>, highest power first.</summary>
37+
private static readonly (int Numerator, int Denominator)[] Quintic =
38+
{ (1, 1), (0, 1), (0, 1), (0, 1), (-3, 1), (1, 1) };
39+
40+
/// <summary>
41+
/// The polynomial with the coefficients <paramref name="coefficients"/> and its roots
42+
/// times <c>10^shift</c>, with each coefficient written out as the rational it is.
43+
/// </summary>
44+
private static Entity Scaled((int Numerator, int Denominator)[] coefficients, int shift)
45+
{
46+
var degree = coefficients.Length - 1;
47+
var x = MathS.Var("x");
48+
Entity? polynomial = null;
49+
for (var i = 0; i <= degree; i++)
50+
{
51+
var (numerator, denominator) = coefficients[i];
52+
if (numerator == 0)
53+
continue;
54+
// The coefficient of x^k is c_k 10^(shift (n - k)).
55+
var power = shift * i;
56+
var scale = BigInteger.Pow(10, System.Math.Abs(power));
57+
var top = power >= 0 ? numerator * scale : numerator;
58+
var bottom = power >= 0 ? denominator : denominator * scale;
59+
Entity coefficient = Number.Rational.Create(
60+
PeterO.Numbers.EInteger.FromString(top.ToString()),
61+
PeterO.Numbers.EInteger.FromString(bottom.ToString()));
62+
// Written as the polynomial is: x^0 is 1 only where x is not 0, which is a condition
63+
// on the answer, and the constant term is the coefficient alone.
64+
var k = degree - i;
65+
var term = k == 0 ? coefficient : k == 1 ? coefficient * x : coefficient * MathS.Pow(x, k);
66+
polynomial = polynomial is null ? term : polynomial + term;
67+
}
68+
return polynomial!;
69+
}
70+
71+
[Theory]
72+
[InlineData(-12)]
73+
[InlineData(-30)]
74+
[InlineData(-45)]
75+
[InlineData(12)]
76+
[InlineData(0)]
77+
public void EveryRootOfTheOcticIsFound(int shift) => EveryRootIsFound(Octic, shift);
78+
79+
[Theory]
80+
[InlineData(-30)]
81+
[InlineData(-45)]
82+
[InlineData(30)]
83+
[InlineData(0)]
84+
public void EveryRootOfTheQuinticIsFound(int shift) => EveryRootIsFound(Quintic, shift);
85+
86+
private static void EveryRootIsFound((int Numerator, int Denominator)[] coefficients, int shift)
87+
{
88+
var answer = Assert.IsType<FiniteSet>(Scaled(coefficients, shift).SolveEquation("x"));
89+
Assert.Equal(coefficients.Length - 1, answer.Count);
90+
var unscaled = Scaled(coefficients, 0);
91+
var back = MathS.Pow(10, -shift);
92+
foreach (var root in answer)
93+
{
94+
// A root of the scaled polynomial, scaled back, is a root of the unscaled one.
95+
var residual = Assert.IsAssignableFrom<Number.Complex>(unscaled.Substitute("x", root * back).EvalNumerical());
96+
Assert.True(residual.Abs() < 1e-40, $"{root} leaves {residual}");
97+
}
98+
// And they are distinct, each to far more than the digits it is checked to.
99+
var values = answer.Select(root => (root * back).EvalNumerical()).Cast<Number.Complex>().ToList();
100+
for (var i = 0; i < values.Count; i++)
101+
for (var j = i + 1; j < values.Count; j++)
102+
Assert.True((values[i] - values[j]).Abs() > 1e-3, $"{values[i]} and {values[j]}");
103+
}
104+
105+
/// <summary>
106+
/// A root far smaller than the others is a root, not a residual of cancellation: the root
107+
/// near <c>1/(3 10^90)</c> beside four of size <c>1.3e-15</c> was rounded onto 0, which the
108+
/// polynomial leaves at <c>10^-150</c>, and 0 was answered among the roots.
109+
/// </summary>
110+
[Theory]
111+
[InlineData("x^5 - 3 * 10^(-60) * x + 10^(-150) = 0", 90)]
112+
[InlineData("x^5 - 3 * x + 10^(-60) = 0", 60)]
113+
public void ARootFarSmallerThanTheOthersIsNotZero(string equation, int digits)
114+
{
115+
var answer = Assert.IsType<FiniteSet>(equation.ToEntity().Solve("x"));
116+
Assert.Equal(5, answer.Count);
117+
Assert.DoesNotContain(answer, root => root.EvalNumerical() is Number.Complex { IsZero: true });
118+
var small = MathS.Pow(3 * MathS.Pow(10, digits), -1);
119+
Assert.Contains(answer, root => ((root - small) / small).EvalNumerical() is Number.Complex relative && relative.Abs() < 1e-20);
120+
}
121+
122+
/// <summary>
123+
/// Solved for the parts of x, a system whose last univariate equation is the octic above with
124+
/// its roots near <c>10^-12</c>: it kept one root of the two. Near <c>10^-30</c> the decimals
125+
/// of each root flushed every term but the constant, and the system read as having no
126+
/// solution answered <c>{ }</c>; it is declined then, and another route answers.
127+
/// </summary>
128+
[Theory]
129+
[InlineData(0)]
130+
[InlineData(12)]
131+
[InlineData(30)]
132+
public void BothRootsOfAnEquationInAModulusAreFound(int scale)
133+
{
134+
var x = $"(10^{scale} * x)";
135+
var equation = $"(1 + i) + 2 * {x} - 3 * {x}^2 + {x} * abs(3 - {x}) = 0".ToEntity();
136+
var answer = Assert.IsType<FiniteSet>(equation.Solve("x"));
137+
Assert.Equal(2, answer.Count);
138+
var unscaled = "(1 + i) + 2 * x - 3 * x^2 + x * abs(3 - x)".ToEntity();
139+
foreach (var root in answer)
140+
{
141+
var residual = Assert.IsAssignableFrom<Number.Complex>(unscaled.Substitute("x", root * MathS.Pow(10, scale)).EvalNumerical());
142+
Assert.True(residual.Abs() < 1e-30, $"{root} leaves {residual}");
143+
}
144+
}
145+
}
146+
}

0 commit comments

Comments
 (0)