Skip to content

Commit 94d6f2c

Browse files
Search for a rational root whatever the scale of the coefficients (#2520)
The rational root search tried the divisors of the first and last coefficients only where both were below a million, to keep factoring them cheap. A polynomial whose roots are those of another times 10^k has coefficients 10^(j k) times the other's, past that bound. So 9x^3 + 9x^2 + 5x + 1 had its root -1/3 found and the same cubic in 10^12 x had -1/(3 10^12) written by Cardano's formula, which the Groebner back-substitution then could not tell made a coefficient 0: the system for the parts of x in 1 + 2x + 3x^2 - 2 Im(x) = 0 with x written as 10^9 x or more was declined. Past the bound, each real root found numerically gives one candidate: a rational root p/q in lowest terms has q dividing the leading coefficient, so the root times it is a whole number, and the root to the working precision, times it and rounded, is that number. Each is checked exactly as before. A first version listed the divisors of coefficients that large instead, tens of thousands of candidates, and a solve with a signum in 10^6 x ran past twenty seconds where master declines in one; this one takes 1.5 s there, against 1.1 s. Within the bound the search is unchanged. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 90593a8 commit 94d6f2c

3 files changed

Lines changed: 114 additions & 5 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,21 @@ filtered as before.
8787
| `"x - 10^(-17) * x^0 = 0".ToEntity().Solve("x")` | `{ }` | `{ 1/100000000000000000 }` |
8888
| `"x^2 - 10^(-40) * x^0 = 0".ToEntity().Solve("x")` | `{ }` | `{ 1/100000000000000000000, -1/100000000000000000000 }` |
8989

90+
### A rational root is found whatever the scale of the coefficients
91+
92+
**Silent: radicals become the rationals they are, and an unsolved equation is solved.** A rational root is searched for
93+
over the divisors of the first and last coefficients, and only where both were below a million, to keep factoring them
94+
cheap. A polynomial whose roots are those of another times `10^k` has coefficients `10^(j k)` times the other's, so it
95+
passed that bound while its coefficients stayed as cheap to factor. Its rational roots were then written by Cardano's
96+
formula. Past the bound, each real root found numerically now gives one candidate: a rational root times the leading
97+
coefficient is a whole number, so the root found to the working precision, times it and rounded, is that number.
98+
Each candidate is checked exactly.
99+
100+
| Input | Was (2.8.0) | Now |
101+
|---|---|---|
102+
| `"x^3 + 1/10^12*x^2 + 5/(9*10^24)*x + 1/(9*10^36) = 0".ToEntity().Solve("x")` | three roots by Cardano's formula | `{ -1/3000000000000, (-1/1500000000000 ± sqrt(-1/1125000000000000000000000)) / 2 }` |
103+
| `"1 + 2*(10^12*x) + 3*(10^12*x)^2 - 2*Im(10^12*x) = 0".ToEntity().Solve("x")` | unsolved | its two roots, `10^-12` times those of the equation in `x` |
104+
90105
### `MathS.Parse` and `Entity.TryParse` return a refused call rather than throw it
91106

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

‎Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialFactoring.cs‎

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//
1+
//
22
// Copyright (c) 2019-2022 Angouri.
33
// AngouriMath is licensed under MIT.
44
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
@@ -46,7 +46,7 @@ internal static class PolynomialFactoring
4646
/// <summary>
4747
/// Rational roots are found by trying divisors of the first and last coefficients,
4848
/// so those have to be small enough to factor cheaply. A polynomial with a
49-
/// coefficient past this is left alone rather than paid for.
49+
/// coefficient past this has its candidates from its numerical roots instead.
5050
/// </summary>
5151
[ConstantField] private static readonly EInteger MaxCoefficientToFactor = EInteger.FromInt32(1000000);
5252

@@ -403,19 +403,62 @@ private static IEnumerable<ERational> RationalRootCandidates(ERational[] coeffic
403403

404404
var constant = whole[0].Abs();
405405
var leading = whole[whole.Length - 1].Abs();
406-
if (constant.IsZero || constant > MaxCoefficientToFactor || leading > MaxCoefficientToFactor)
406+
if (constant.IsZero)
407407
return Enumerable.Empty<ERational>();
408+
if (constant > MaxCoefficientToFactor || leading > MaxCoefficientToFactor)
409+
return NumericalCandidates(whole, leading);
410+
var ofConstant = Divisors(constant);
411+
var ofLeading = Divisors(leading).ToList();
408412

409413
var candidates = new List<ERational>();
410-
foreach (var p in Divisors(constant))
411-
foreach (var q in Divisors(leading))
414+
foreach (var p in ofConstant)
415+
foreach (var q in ofLeading)
412416
{
413417
candidates.Add(ERational.Create(p, q));
414418
candidates.Add(ERational.Create(p.Negate(), q));
415419
}
416420
return candidates.Distinct();
417421
}
418422

423+
/// <summary>
424+
/// The rational roots a polynomial with the whole <paramref name="coefficients"/>, lowest
425+
/// power first, can have, where its first or last coefficient is too large to factor: one
426+
/// for each of its real roots, found numerically.
427+
/// </summary>
428+
/// <remarks>
429+
/// A rational root <c>p/q</c> in lowest terms has <c>q</c> dividing the leading coefficient
430+
/// <c>c_n</c>, so it times <c>c_n</c> is a whole number, and the real root found to the
431+
/// working precision, times <c>c_n</c> and rounded, is that number. Each candidate is still
432+
/// checked exactly. A polynomial whose roots are those of another times <c>10^k</c> has
433+
/// coefficients <c>10^(j k)</c> times the other's, past any bound on their size, so
434+
/// <c>9x^3 + 9x^2 + 5x + 1</c> had its root <c>-1/3</c> found and the same cubic in
435+
/// <c>10^12 x</c> had <c>-1/(3 10^12)</c> written by Cardano's formula; and the system for the
436+
/// parts of x in <c>1 + 2x + 3x^2 - 2 Im(x) = 0</c> with x written as <c>10^12 x</c> could not
437+
/// tell that such a root made a coefficient 0, and was declined. Searching the divisors of
438+
/// coefficients that large instead was tens of thousands of candidates, and a solve that asked
439+
/// for it in every case of a signum ran past twenty seconds.
440+
/// </remarks>
441+
private static IEnumerable<ERational> NumericalCandidates(EInteger[] coefficients, EInteger leading)
442+
{
443+
if (SquareFreeDecomposition.Decompose(IntegerPolynomial.Create(coefficients).PrimitivePart()) is not { } parts)
444+
return Enumerable.Empty<ERational>();
445+
var context = MathS.Settings.DecimalPrecisionContext.Value;
446+
var whole = EDecimal.FromEInteger(leading);
447+
var candidates = new List<ERational>();
448+
foreach (var part in parts)
449+
{
450+
if (part.Factor.Degree < 1
451+
|| Algebra.NumericalSolving.DurandKerner.Roots(part.Factor, context) is not { } roots)
452+
continue;
453+
foreach (var root in roots)
454+
if (root.ImaginaryPart.EDecimal.IsZero)
455+
candidates.Add(ERational.Create(
456+
root.RealPart.EDecimal.Multiply(whole).RoundToIntegerNoRoundedFlag(EContext.Unlimited.WithRounding(ERounding.HalfEven)).ToEInteger(),
457+
leading));
458+
}
459+
return candidates.Distinct();
460+
}
461+
419462
private static EInteger Lcm(EInteger a, EInteger b) => a.Divide(a.GreatestCommonDivisor(b)).Multiply(b);
420463

421464
private static IEnumerable<EInteger> Divisors(EInteger n)
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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.Extensions;
9+
using Xunit;
10+
using static AngouriMath.Entity;
11+
using static AngouriMath.Entity.Set;
12+
13+
namespace AngouriMath.Tests.Algebra
14+
{
15+
/// <summary>
16+
/// A rational root is searched for over the divisors of the first and last coefficients, and
17+
/// was only where both were below a million. The cubic <c>9x^3 + 9x^2 + 5x + 1</c>, with its
18+
/// roots scaled by <c>10^-12</c>, has coefficients past that and as cheap to factor, and its
19+
/// rational root <c>-1/(3 10^12)</c> was written by Cardano's formula. A system that needed it
20+
/// exactly, for the parts of x in <c>1 + 2x + 3x^2 - 2 Im(x) = 0</c> with x written as
21+
/// <c>10^12 x</c>, was declined. Found by solving generated equations with <c>x</c> written as
22+
/// <c>10^12 x</c>; no issue was filed.
23+
/// </summary>
24+
[Trait("Area", "Algebra")]
25+
public sealed class ARationalRootIsFoundAtAnyScaleTest
26+
{
27+
[Theory]
28+
[InlineData("x^3 + 1/10^12*x^2 + 5/(9*10^24)*x + 1/(9*10^36) = 0", "-1/3000000000000")]
29+
[InlineData("9*10^36*x^3 + 9*10^24*x^2 + 5*10^12*x + 1 = 0", "-1/3000000000000")]
30+
[InlineData("x^3 + 1/10^6*x^2 + 5/(9*10^12)*x + 1/(9*10^18) = 0", "-1/3000000")]
31+
[InlineData("x^3 + 1/10^30*x^2 + 5/(9*10^60)*x + 1/(9*10^90) = 0", "-1/3000000000000000000000000000000")]
32+
public void TheRationalRootIsExact(string equation, string root)
33+
=> Assert.Contains(root.ToEntity().Evaled, Assert.IsType<FiniteSet>(equation.ToEntity().Solve("x")));
34+
35+
[Theory]
36+
[InlineData("10^9")]
37+
[InlineData("10^12")]
38+
public void AnEquationInAPartOfXIsSolvedAtScale(string scale)
39+
{
40+
var x = $"({scale} * x)";
41+
var answer = Assert.IsType<FiniteSet>($"1 + 2 * {x} + 3 * {x}^2 - 2 * Im({x}) = 0".ToEntity().Solve("x"));
42+
Assert.Equal(2, answer.Count);
43+
var unscaled = "1 + 2 * x + 3 * x^2 - 2 * Im(x)".ToEntity();
44+
foreach (var root in answer)
45+
{
46+
var residual = Assert.IsAssignableFrom<Number.Complex>(unscaled.Substitute("x", root * scale.ToEntity()).EvalNumerical());
47+
Assert.True(residual.Abs() < 1e-30, $"{root} leaves {residual}");
48+
}
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)