From ecb1f5b20f4ecd024b614d08a25bbeadce67bdad Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Sun, 15 Nov 2026 16:53:12 +0000 Subject: [PATCH 1/2] Solve one equation at the default zero tolerance, and decline where an exact root is shown not to be one (#2448) With (1 + sqrt(2))^n = P + Q sqrt(2), x^2 + (P_70 + Q_70 sqrt(2)) x - 3 was solved as { -2 P_70 }, which leaves -2; x^2 + (P_70 - Q_70 sqrt(2)) x - 3 as { sqrt(3), -sqrt(3) }, the coefficient dropped; and at n = 20 the discriminant b^2 + 12 was read as 12. EquationSolver.Solve ran under PrecisionErrorZeroRange = 1e-12, which widens the downcasting tolerance from 1e-50, and checked its roots inside the same scope. The override is gone: SolveEquation now solves as Solve on the equation already did, and n = 20..60 come out right. Where the default 1e-50 still rounds, WithoutSpuriousRoots, shared by both entry points, now weighs an exact root against an interval: - a root with only exact numbers in it, in an equation with only exact numbers, whose residual's PreciseEvaluation enclosure leaves out zero, declines the equation (a ConditionalSet), rather than being dropped, which would answer an incomplete set; - a root the decimal evidence took for spurious is kept where the residual is exact and algebraic and its enclosure holds zero: the small root -b/2 + sqrt(b^2 + 12)/2 keeps 46 digits at a hundred and left 5.9e-48 against terms of 3, which dropped it from 70 to 120. The enclosure is taken only where the residual, evaluated without downcasting at the working digits plus those of the largest number in the tree, is above 1e-95: an interval for every exact root doubled the allocation of solving x^2 + x + 1. A system whose elimination leaves an equation unsolved at a leaf is declined too, where the rows of the other branches were returned as all of them; RowsThatHold uses the same enclosure-aware evidence. Measured, roots checked against the true ones at 400 digits, 2.7.0/master -> branch, SolveEquation: n = 5, 10 right -> right n = 20..60 wrong (+ at 40..60 unsolved) -> right n = 70..120 + wrong { -2P } -> right n = 70..120 - wrong { (-b +- 2 sqrt(3))/2 } or { +-sqrt(3) } -> declined n = 140, 200 wrong -> declined n = 160 + wrong -> declined; - wrong -> still wrong (residual near 1e-123, past a hundred digits) Solve on the equation: right to 60 before and after; 70..120 + missed the small root -> both roots; the rest as above. System y^2 - 2, x^2 + (P - Q y) x - 3: n = 20..60 declined -> four rows; 70..200 declined -> declined. With the override removed alone, n = 80 and 120 came back with 3 and 2 of the 4 rows; the leaf decline is what stops that. Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 32 ++- .../Continuous/Solvers/EquationSolver.cs | 81 ++----- .../Solvers/EquationSolver/SolveStatement.cs | 220 +++++++++++++++++- .../UnitTests/Common/SolverRegressionTest.cs | 62 ++++- 4 files changed, 323 insertions(+), 72 deletions(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index d3aa330ec..3b341c47f 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -113,6 +113,35 @@ matrix, so the operand is no longer multiplied into the components as a number --- +### One equation is solved at the default zero tolerance, and a root shown not to be one declines it + +**Silent: wrong roots are now right, or no answer.** `SolveEquation` solved under a zero tolerance of `1e-12`, where the +rest of the library works to `1e-50`, so a coefficient that nearly cancels was read as zero or rounded into the +discriminant. It now solves at the default, as `Solve` on the equation already did. Where the default still rounds, a root +with only exact numbers in it whose residual an interval shows is not zero leaves the equation unsolved, and a root that +the residual's evaluation alone took for spurious is kept where an interval holds zero +([#2448](https://github.com/asc-community/AngouriMath/issues/2448)). `P + Q sqrt(2) = (1 + sqrt(2))^n`: + +| Input | Was (2.7.0) | Now | +|---|---|---| +| `"x^2 + (22619537 - 15994428 * sqrt(2)) * x - 3".SolveEquation("x")`, `n = 20` | `{ (-(22619537 + -15994428 * sqrt(2)) - 2 * sqrt(3)) / 2, (-(22619537 + -15994428 * sqrt(2)) + 2 * sqrt(3)) / 2 }` | `{ (-b - sqrt(b ^ 2 - (-12))) / 2, (-b + sqrt(b ^ 2 - (-12))) / 2 }` for `b = 22619537 + -15994428 * sqrt(2)` | +| `"x^2 + (311363698964240484013304163 + 220167382952941249990598278 * sqrt(2)) * x - 3".SolveEquation("x")`, `n = 70` | `{ -622727397928480968026608326 }` | both roots, as above | +| `"x^2 + (311363698964240484013304163 - 220167382952941249990598278 * sqrt(2)) * x - 3".SolveEquation("x")`, `n = 70` | `{ sqrt(3), -sqrt(3) }` | `{ x : x ^ 2 + (311363698964240484013304163 - 220167382952941249990598278 * sqrt(2)) * x = 3 }` | +| `"x^2 + (311363698964240484013304163 + 220167382952941249990598278 * sqrt(2)) * x - 3 = 0".Solve("x")`, `n = 70` | the root near `-2P` only | both roots | + +Measured for `n` = 5, 10, 20 to 60, 70 to 120, 140, 160 and 200, with each root checked against the true one at 400 +digits. `SolveEquation` was wrong for both signs from 20 up, but for `P + Q sqrt(2)` at 40 to 60, which it left unsolved; +it is right now for both up to 60 and for `P + Q sqrt(2)` up to 120. `Solve` on the equation was right to 60 and missed the +small root of `P + Q sqrt(2)` from 70 to 120, which it now finds. What is left unsolved now was wrong: `P - Q sqrt(2)` from +70 and `P + Q sqrt(2)` from 140. `P - Q sqrt(2)` at 160 is still answered wrongly, with a residual near `1e-123`, past +the hundred digits evaluation works to; downcasting, which v3 removes, is what reads it as zero. + +A system whose elimination leaves one of its equations unsolved is declined too, where the rows it found were +returned as all of them. `MathS.Equations("y^2 - 2", "x^2 + (P - Q y) * x - 3").Solve("x", "y")` was declined for +`n` = 20 to 60, and is answered now with its four rows. + +--- + ### A system row that is not a solution declines the system **Silent: a wrong row is now no answer.** With `P + Q sqrt(2) = (1 + sqrt(2))^70`, the coefficient `P - Q y` is @@ -125,7 +154,8 @@ the system ([#2446](https://github.com/asc-community/AngouriMath/issues/2446)). |---|---|---| | `MathS.Equations("y^2 - 2", "x^2 + (311363698964240484013304163 - 220167382952941249990598278 * y) * x - 3").Solve("x", "y")` | `[[-622727397928480968026608326, -sqrt(2)]]` | `null` | -The same system for the exponents 20 to 60 was declined already, and for 10 it is still answered with its four rows. +The same system for the exponents 20 to 60 was declined already, and for 10 it is still answered with its four rows; 20 +to 60 are answered now, in the entry above. For 80 to 160 it was answered with the one row `[-2P, -sqrt(2)]` too, and for 140 and 200 with `[sqrt(3), sqrt(2)]` and `[-sqrt(3), sqrt(2)]` besides, which leave `sqrt(3) (P - Q sqrt(2))`; each of those is declined now. diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs index 53b8b0f3a..e0b1bb205 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver.cs @@ -26,7 +26,6 @@ internal static Set Solve(Entity equation, Variable x) // https://github.com/asc-community/AngouriMath/issues/1673 if (equation is Equalsf(var left, var right)) equation = left - right; - using var _ = MathS.Settings.PrecisionErrorZeroRange.Set(1e-12m); using var __ = MathS.Settings.FloatToRationalIterCount.Set(0); using var ___ = MathS.Settings.MaxExpansionTermCount.Set(50); var solutions = AnalyticalEquationSolver.Solve(equation, x); @@ -173,7 +172,8 @@ internal static Set Solve(Entity equation, Variable x) : null; int initVarCount = vars.Length; - var res = InSolveSystem(equations, vars, Sumf.Sum(equations), ledger); + if (InSolveSystem(equations, vars, Sumf.Sum(equations), ledger) is not { } res) + return null; foreach (var tuple in res) if (tuple.Count != initVarCount) throw new AngouriBugException("InSolveSystem incorrect output"); @@ -271,7 +271,7 @@ internal static Set Solve(Entity equation, Variable x) /// /// /// A row is dropped on the evidence a root of one equation is dropped on, - /// : an equation that, with the row put + /// : an equation that, with the row put /// in, has no symbol left and is a number away from zero, or is no finite number at all, as /// x ln(y) is at (0, 0). Such a row is no solution for any value of anything, /// so dropping it loses none. @@ -316,11 +316,11 @@ internal static Set Solve(Entity equation, Variable x) replacements[variables[index]] = row[index]; var residuals = equations.Select(equation => equation.Substitute(replacements)).ToList(); if (residuals.Any(residual => !residual.Vars.Any() - && (residual.Evaled is Complex { IsFinite: false } || StatementSolver.IsEvidenceAgainst(residual)))) + && (residual.Evaled is Complex { IsFinite: false } || StatementSolver.IsEvidenceAgainstUnlessEnclosed(residual)))) continue; if (residuals.Any(residual => residual.Vars.Any() && StatementSolver.IsEvidenceAgainst(AtASamplePoint(residual, own)))) return null; - if (IsExact(row) && residuals.Any(residual => !residual.Vars.Any() && IsShownNotZero(residual))) + if (IsExact(row) && residuals.Any(residual => !residual.Vars.Any() && StatementSolver.IsShownNotZero(residual))) return null; kept.Add(row); } @@ -329,56 +329,7 @@ internal static Set Solve(Entity equation, Variable x) /// Whether no entry of has a number in it that is not exact. private static bool IsExact(List row) - => !row.Any(entry => entry.Nodes.Any(node => node is Number { IsExact: false })); - - /// - /// Whether an interval enclosing , a number with no symbol in - /// it, leaves out zero. Interval arithmetic rounds each bound outward, so that is a proof - /// and not an estimate; an interval that holds zero, or that cannot be worked out, proves - /// nothing either way. - /// - /// - /// To as many decimal places as evaluation works to significant digits: a residual under - /// that is what the tolerance takes for zero whatever the terms are, and one that - /// evaluation took for zero above it is under about half of the digits next to its terms. - /// The digits are - /// significant ones, so where the terms are large the first interval is wider than that, - /// and it is worked out once more with the digits the terms take besides: with - /// (1 + sqrt(2))^140 in the coefficients the terms are near 1e107, and the - /// residual -2 is inside an interval of a hundred digits. - /// - private static bool IsShownNotZero(Entity residual) - { - var precision = MathS.Settings.DecimalPrecisionContext.Value.Precision; - var digits = precision.IsZero || !precision.CanFitInInt32() ? 100 : System.Math.Max(precision.ToInt32Unchecked(), 30); - if (Numerics.PreciseEvaluation.Of(residual, digits) is not { } enclosure) - return false; - if (Excludes(enclosure)) - return true; - var width = PeterO.Numbers.EDecimal.Max( - enclosure.Re.High.Subtract(enclosure.Re.Low), enclosure.Im.High.Subtract(enclosure.Im.Low)); - if (width.IsZero) - return false; - // The decimal exponent of the width: how many more digits put it under 10^-digits. - // Ten or fewer are what rounding leaves of terms near one, which is every row whose - // terms are not large, and are not worth a second evaluation. - var magnitude = width.Exponent.Add(width.UnsignedMantissa.GetDigitCountAsEInteger()).Subtract(1); - var more = magnitude.Add(digits); - if (more.CompareTo(10) <= 0) - return false; - if (!more.CanFitInInt32() || more.ToInt32Unchecked() > MostMoreDigits) - more = MostMoreDigits; - return Numerics.PreciseEvaluation.Of(residual, digits + more.ToInt32Unchecked()) is { } finer && Excludes(finer); - - static bool Excludes(Numerics.PreciseComplexInterval enclosure) - => enclosure.Re.Mignitude.Sign > 0 || enclosure.Im.Mignitude.Sign > 0; - } - - /// - /// The most digits adds for large terms, which bounds what one - /// residual costs: a thousand digits is terms past 1e900. - /// - private const int MostMoreDigits = 1000; + => row.All(StatementSolver.IsExact); /// /// without a row that is a copy of another: one equal to an @@ -451,7 +402,10 @@ private static Entity AtASamplePoint(Entity residual, HashSet own) return residual; } - /// Solves system of equations + /// + /// Solves system of equations, or where an equation is left + /// unsolved on the way and the rows found would not be all of them + /// /// of /// /// of s, @@ -466,7 +420,7 @@ private static Entity AtASamplePoint(Entity residual, HashSet own) /// because the recursion passes it along and a caller may have none; where it is /// absent this is unbounded, which is what it always was. /// - internal static List> InSolveSystem( + internal static List>? InSolveSystem( List equations, ReadOnlySpan vars, Entity nameSource, BudgetLedger? ledger = null) { @@ -494,6 +448,13 @@ internal static List> InSolveSystem( // what the answer is in the same way the trigonometric solvers say it with n_1. if (solutions == MathS.Sets.C) return new() { new List { Variable.CreateUnique(nameSource, "t") } }; + // An equation left unsolved has roots that were not found, and no rows here would + // say it has none: the rows of the other branches would read as every solution. + // y^2 - 2, x^2 + (P - Q y) x - 3, with (1 + sqrt(2))^70 = P + Q sqrt(2), declines + // its equation in x at y = sqrt(2), and was answered with one row of four. + // https://github.com/asc-community/AngouriMath/issues/2448 + if (solutions is ConditionalSet) + return null; return new(); } var result = new List>(); @@ -518,7 +479,10 @@ internal static List> InSolveSystem( rest.RemoveAt(i); foreach (var sol in sols) - foreach (var j in InSolveSystem(rest.Select(eq => eq.Substitute(var, sol)).ToList(), remainingVars, nameSource, ledger)) + { + if (InSolveSystem(rest.Select(eq => eq.Substitute(var, sol)).ToList(), remainingVars, nameSource, ledger) is not { } rows) + return null; + foreach (var j in rows) { replacements.Clear(); for (int varid = 0; varid < remainingVars.Length; varid++) @@ -526,6 +490,7 @@ internal static List> InSolveSystem( j.Add(sol.Substitute(replacements).InnerSimplified); result.Add(j); } + } if (result.Count > 0) return result; diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs index c8691bb9e..92ea601b8 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs @@ -40,22 +40,50 @@ private static Entity Minus(Entity left, Entity right) /// individual rewrites cannot always carry a condition that survives the chain of /// substitutions that follows, so the answers are checked once, here, against the /// equation as the caller wrote it. + /// + /// A root with only exact numbers in it that the check keeps, and that an interval enclosing + /// its residual shows is none, leaves the equation unsolved; see + /// . + /// /// internal static Set WithoutSpuriousRoots(Set roots, Entity equation, Variable x) { - if (roots is not FiniteSet finite || !finite.Any(root => IsSpurious(equation, x, root))) + if (roots is not FiniteSet finite) + return roots; + List? survivors = null; + var index = 0; + foreach (var root in finite) + { + switch (Verdict(equation, x, root)) + { + case RootVerdict.ShownNotARoot: + return Unsolved(equation, x); + case RootVerdict.Spurious: + survivors ??= finite.Take(index).ToList(); + break; + default: + survivors?.Add(root); + break; + } + index++; + } + if (survivors is null) return roots; - var kept = finite.Where(root => !IsSpurious(equation, x, root)).ToSet(); + var kept = survivors.ToSet(); // A polynomial of degree one or more has a root over the complex numbers, so where every // candidate for one fails, what failed is the solver, and the empty set left would claim // there is no root: (x + 1)^3 = 2 was { } while Cardano's C was 0 for a shifted cube, and // 31x^4 - 62x^3 + 33x^2 - 2x - 1 = 0 while a biquadratic quartic was shifted by -b a / 4. // Left unsolved instead, which says only that the roots were not found. if (kept.Count == 0 && IsAPolynomialWithARoot(equation, x)) - return new ConditionalSet(x, equation is Minusf(var left, var right) ? left.Equalizes(right) : equation.Equalizes(0)); + return Unsolved(equation, x); return kept; } + /// as a condition on : the roots were not found. + private static Set Unsolved(Entity equation, Variable x) + => new ConditionalSet(x, equation is Minusf(var left, var right) ? left.Equalizes(right) : equation.Equalizes(0)); + /// /// Whether is a polynomial in with numbers /// for coefficients and a degree of one or more, read over the complex numbers, where such a @@ -165,7 +193,7 @@ internal static Set UnsolvedWhereIndependenceIsDenied(Set roots, Entity conditio /// that a root is only ever dropped on positive evidence against it. A function /// undefined at exact arguments is such evidence; see . /// - private static bool IsSpurious(Entity equation, Variable x, Entity root) + private static RootVerdict Verdict(Entity equation, Variable x, Entity root) { // A root that still mentions the variable it solves for is the equation // rearranged, not an answer to it: x = sqrt(-1 - x) says nothing about x. This @@ -181,13 +209,177 @@ private static bool IsSpurious(Entity equation, Variable x, Entity root) // that, so the next caller to forget is caught here rather than in a bug report. // https://github.com/asc-community/AngouriMath/issues/744 if (root.ContainsNode(x)) - return true; + return RootVerdict.Spurious; if (root.Vars.Any()) + return RootVerdict.Kept; + var substituted = equation.Substitute(x, root); + if (IsUndefinedExactly(substituted)) + return RootVerdict.Spurious; + if (IsEvidenceAgainstUnlessEnclosed(substituted)) + return RootVerdict.Spurious; + return !substituted.Vars.Any() && IsAboveTheIntervalFloor(equation, x, root) && IsShownNotZero(substituted) + ? RootVerdict.ShownNotARoot + : RootVerdict.Kept; + } + + /// What does with a root. + private enum RootVerdict + { + /// Kept: nothing shows it is not a root. + Kept, + /// Dropped: it came of a rewrite that widened the domain, and fails the equation as written. + Spurious, + /// + /// Declines the equation. The root has only exact numbers in it, so it is a root only + /// where its residual is exactly zero, and an interval enclosing the residual leaves + /// zero out, however small the residual is next to the terms. That the check above + /// passed it means rounding reached the solve, which can have lost a true root as well + /// as made this one, so it is not dropped, which would answer an incomplete set. In + /// x^2 + (P - Q sqrt(2)) x - 3, with (1 + sqrt(2))^70 = P + Q sqrt(2), + /// downcasting reads b^2 + 12 as 12, and the roots came back as + /// (-b +- 2 sqrt(3)) / 2, each leaving -b^2 / 4, about -6.4e-55, against + /// terms near 3. Rounding reaches an exact solve through downcasting, which v3 + /// removes; the decline is to be reconsidered then, and the check kept. + /// #2448, + /// #1019 + /// + ShownNotARoot, + } + + /// Whether has no number in it that is not exact. + internal static bool IsExact(Entity entity) + => !entity.Nodes.Any(node => node is Number { IsExact: false }); + + /// + /// Whether an interval enclosing , a number with no symbol in + /// it, leaves out zero. Interval arithmetic rounds each bound outward, so that is a proof + /// and not an estimate; an interval that holds zero, or that cannot be worked out, proves + /// nothing either way. + /// + /// + /// To as many decimal places as evaluation works to significant digits: a residual under + /// that is what the tolerance takes for zero whatever the terms are, and one that + /// evaluation took for zero above it is under about half of the digits next to its terms. + /// The digits are significant ones, so where the terms are large the first interval is wider than that, + /// and it is worked out once more with the digits the terms take besides: with + /// (1 + sqrt(2))^140 in the coefficients the terms are near 1e107, and the + /// residual -2 is inside an interval of a hundred digits. + /// + internal static bool IsShownNotZero(Entity residual) => ExcludesZero(residual) is true; + + /// + /// Whether an interval enclosing leaves out zero, as + /// works it out; where it holds zero, + /// and where no interval can be worked out. + /// + private static bool? ExcludesZero(Entity residual) + { + var digits = IntervalDigits(); + if (Numerics.PreciseEvaluation.Of(residual, digits) is not { } enclosure) + return null; + if (Excludes(enclosure)) + return true; + var width = PeterO.Numbers.EDecimal.Max( + enclosure.Re.High.Subtract(enclosure.Re.Low), enclosure.Im.High.Subtract(enclosure.Im.Low)); + if (width.IsZero) + return false; + // The decimal exponent of the width: how many more digits put it under 10^-digits. + // Ten or fewer are what rounding leaves of terms near one, which is every residual whose + // terms are not large, and are not worth a second evaluation. + var magnitude = width.Exponent.Add(width.UnsignedMantissa.GetDigitCountAsEInteger()).Subtract(1); + var more = magnitude.Add(digits); + if (more.CompareTo(10) <= 0) return false; + if (!more.CanFitInInt32() || more.ToInt32Unchecked() > MostMoreDigits) + more = MostMoreDigits; + return Numerics.PreciseEvaluation.Of(residual, digits + more.ToInt32Unchecked()) is { } finer && Excludes(finer); + + static bool Excludes(Numerics.PreciseComplexInterval enclosure) + => enclosure.Re.Mignitude.Sign > 0 || enclosure.Im.Mignitude.Sign > 0; + } + + /// + /// The decimal places first encloses a residual to: as many as + /// evaluation works to significant digits. + /// + private static int IntervalDigits() + { + var precision = MathS.Settings.DecimalPrecisionContext.Value.Precision; + return precision.IsZero || !precision.CanFitInInt32() ? 100 : System.Math.Max(precision.ToInt32Unchecked(), 30); + } + + /// + /// Whether and have only exact numbers in + /// them, and the residual, evaluated without downcasting, is further from zero than rounding + /// leaves of a true root's: only such a residual is enclosed by . + /// + /// + /// + /// The evaluation is what keeps the common case cheap. An interval evaluation of each exact + /// root was twice the allocation of solving x^2 + x + 1, whose roots leave 0 + /// here and are not enclosed; this costs about a tenth of that. + /// + /// + /// Without downcasting, because downcasting is what made the roots wrong, and it reads what + /// such a root leaves as zero too: -b^2 / 4 evaluates to 0 with it, and to + /// -6.4e-55 without. A fresh tree, since keeps a value + /// with the precision it was computed at and not with this setting. With the digits of the + /// largest number in the tree besides, where those are more than ten: at + /// (1 + sqrt(2))^140 = P + Q sqrt(2), P - Q sqrt(2) is 2.6e-54 with + /// P near 1.9e53, which takes 108 digits to tell from zero. + /// + /// + private static bool IsAboveTheIntervalFloor(Entity equation, Variable x, Entity root) + { var substituted = equation.Substitute(x, root); - return IsUndefinedExactly(substituted) || IsEvidenceAgainst(substituted); + var mostDigits = 0; + foreach (var node in substituted.Nodes) + switch (node) + { + case Number { IsExact: false }: + return false; + case Rational rational: + mostDigits = System.Math.Max(mostDigits, DigitCount(rational)); + break; + case Complex { RealPart: Rational re, ImaginaryPart: Rational im }: + mostDigits = System.Math.Max(mostDigits, System.Math.Max(DigitCount(re), DigitCount(im))); + break; + } + var digits = IntervalDigits(); + Entity value; + using (MathS.Settings.DowncastingEnabled.Set(false)) + if (mostDigits > 10) + using (MathS.Settings.DecimalPrecisionContext.Set( + MathS.Settings.DecimalPrecisionContext.Value.WithPrecision(digits + System.Math.Min(mostDigits, MostMoreDigits)))) + value = substituted.Evaled; + else + value = substituted.Evaled; + if (value is not Complex residual) + return false; + var floor = EDecimal.Create(EInteger.One, EInteger.FromInt32(TrueRootFloorDigits - digits)); + return residual.RealPart.EDecimal.Abs().GreaterThan(floor) || residual.ImaginaryPart.EDecimal.Abs().GreaterThan(floor); + + static int DigitCount(Rational rational) + { + var count = EInteger.Max(rational.ERational.Numerator.Abs().GetDigitCountAsEInteger(), + rational.ERational.Denominator.GetDigitCountAsEInteger()); + return count.CanFitInInt32() ? count.ToInt32Unchecked() : int.MaxValue; + } } + /// + /// How many of rounding takes from a true root's residual, + /// by : the roots of x^2 + 3x - 5 leave + /// 1e-98 at a hundred digits. + /// + private const int TrueRootFloorDigits = 5; + + /// + /// The most digits adds for large terms, which bounds what one + /// residual costs: a thousand digits is terms past 1e900. + /// + private const int MostMoreDigits = 1000; + /// /// Whether , with no symbol left in it, has no value because /// some function in it is undefined at its arguments: a node whose arguments are all exact @@ -243,6 +435,22 @@ internal static bool IsEvidenceAgainst(Entity substituted) return size.GreaterThan(LargestTerm(substituted).Multiply(RelativeResidualTolerance)); } + /// + /// , weighed against an interval where + /// is exact numbers in sums, products, quotients and rational + /// powers, whose enclosures are tight: one that holds zero says the residual is what + /// rounding left, and is no evidence. + /// + /// + /// The small root of x^2 + b x - 3, with b = (1 + sqrt(2))^70 near + /// 6e26, is -b/2 + sqrt(b^2 + 12)/2, and at a hundred digits that difference + /// keeps 46 digits of the root's 4.8e-27, which leaves 5.9e-48 against terms + /// of 3: over the bound for exact numbers, and rounding. + /// #2448 + /// + internal static bool IsEvidenceAgainstUnlessEnclosed(Entity substituted) + => IsEvidenceAgainst(substituted) && !(IsExactAndAlgebraic(substituted) && ExcludesZero(substituted) is false); + /// /// Whether is exact numbers in sums, products, quotients and /// rational powers, which evaluation carries to the working precision. A function, a constant diff --git a/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs b/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs index e4465f4c0..1366bf87b 100644 --- a/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs @@ -292,17 +292,19 @@ public void Issue2425_AnExponentialEquationOverTheRealsHasOnlyRealRoots(string e // in the second equation, about -2, and its four solutions were lost. Each equation is a // quadratic in x for each y, so every answer has four rows; each row is put back into // both equations and enclosed, by interval arithmetic, within 1e-80 of zero. Declining - // is allowed where the coefficients are too close to rounding to settle, and n = 10 is - // answered today and must stay answered. At n = 140 the terms are near 1e107, past the + // is allowed where the coefficients are too close to rounding to settle, and n = 10 to 60 + // are answered today and must stay answered: those were declined while one equation was + // solved at a zero tolerance of 1e-12 (https://github.com/asc-community/AngouriMath/issues/2448). + // At n = 70 the equation in x is declined at y = sqrt(2). At n = 140 the terms are near 1e107, past the // hundred digits evaluation works to, and the rows [sqrt(3), sqrt(2)] and // [-sqrt(3), sqrt(2)] were answered too. [Theory] [InlineData(10, true)] - [InlineData(20, false)] - [InlineData(30, false)] - [InlineData(40, false)] - [InlineData(50, false)] - [InlineData(60, false)] + [InlineData(20, true)] + [InlineData(30, true)] + [InlineData(40, true)] + [InlineData(50, true)] + [InlineData(60, true)] [InlineData(70, false)] [InlineData(140, false)] [InlineData(200, false)] @@ -331,6 +333,52 @@ public void Issue2446_EveryRowOfASystemWithACancellingCoefficientIsASolution(int } } + // https://github.com/asc-community/AngouriMath/issues/2448 + // The declines here come of downcasting, which v3 removes: + // https://github.com/asc-community/AngouriMath/issues/1019#issuecomment-5754734225 + // P and Q are the Pell numbers with (1 + sqrt(2))^n = P + Q sqrt(2), so P - Q sqrt(2) is + // (1 - sqrt(2))^n, which is 1.6e-27 for n = 70. With the coefficient P + Q sqrt(2) the + // roots are near -2P and 3 / (2P), and the answer was { -2P }, which leaves exactly -2; + // with P - Q sqrt(2) it was { sqrt(3), -sqrt(3) }, the coefficient dropped, and at n = 20 + // the discriminant b^2 + 12 was read as 12. Both entry points are asked, since the solve + // of an equation and of a statement put their roots back the same way. Each answer must + // have both roots, each enclosed, by interval arithmetic, within 1e-80 of zero when put + // back. Declining is allowed only where the coefficient is too close to rounding to + // settle: at n = 70 the default downcasting still reads b^2 + 12 as 12 for P - Q sqrt(2). + [Theory] + [InlineData(20, "+", true)] + [InlineData(20, "-", true)] + [InlineData(40, "+", true)] + [InlineData(40, "-", true)] + [InlineData(70, "+", true)] + [InlineData(70, "-", false)] + public void Issue2448_EveryRootOfAQuadraticWithACancellingCoefficientIsARoot(int n, string sign, bool answered) + { + System.Numerics.BigInteger p = 1, q = 0; + for (var i = 0; i < n; i++) + (p, q) = (p + 2 * q, p + q); + var equation = $"x^2 + ({p} {sign} {q} * sqrt(2)) * x - 3".ToEntity(); + foreach (var solutions in new[] { MathS.SolveEquation(equation, "x"), equation.Equalizes(0).Solve("x") }) + { + if (solutions is not Entity.Set.FiniteSet roots) + { + Assert.False(answered, $"declined an equation that is answered: {solutions}"); + Assert.IsType(solutions); + continue; + } + Assert.Equal(2, roots.Count); + foreach (var root in roots) + { + var residual = equation.Substitute("x", root); + var enclosure = AngouriMath.Numerics.PreciseEvaluation.Of(residual, 200); + Assert.True(enclosure is { } value + && value.Re.Magnitude.CompareTo(PeterO.Numbers.EDecimal.FromString("1E-80")) <= 0 + && value.Im.Magnitude.CompareTo(PeterO.Numbers.EDecimal.FromString("1E-80")) <= 0, + $"{root} leaves {residual.Evaled} in {equation}"); + } + } + } + // The complex reading is untouched: e^x + 1 = 0 has the root i pi there. [Fact] public void Issue2425_OverTheComplexNumbersTheRootIsKept() From 542031f68494efefcfafa3ab7b5f02f14559950b Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Sun, 15 Nov 2026 18:53:49 +0000 Subject: [PATCH 2/2] Record SolveHard's lower allocation in the performance baseline The kernel performance gate on this PR's first run reported SolveHard at 8,514,589 B/op, 10.6% below the 9,526,556 recorded at 190a6c84, and every other gated benchmark within its band. The file is that run's own measurement (benchmark-results artifact of run 43747235590), copied over the baseline as the gate asks. Co-Authored-By: Claude Opus 5.5 --- .../DotnetBenchmark/performance-baseline.json | 72 +++++++++---------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/Sources/Tests/DotnetBenchmark/performance-baseline.json b/Sources/Tests/DotnetBenchmark/performance-baseline.json index 661a0effb..525ae45e7 100644 --- a/Sources/Tests/DotnetBenchmark/performance-baseline.json +++ b/Sources/Tests/DotnetBenchmark/performance-baseline.json @@ -1,94 +1,94 @@ { "comment": "Allocated bytes and mean nanoseconds per operation for the popular use cases of https://github.com/asc-community/AngouriMath/issues/746. Checked by PerformanceGate.cs; see Sources/AngouriMath/Docs/WhatsNew/version_performance_control.md for when updating it is legitimate.", "benchmark": "CommonFunctionsInterVersion", - "commit": "190a6c8427a0e2d5e8e1c9e58368453e82891067", - "measuredOn": "2026-11-01", - "runtime": ".NET 10.0.14", + "commit": "6790f7ca40adde0d5e83253aac9cd6e6c9e2cadb", + "measuredOn": "2026-11-15", + "runtime": ".NET 10.0.15", "machine": "Ubuntu 26.04.1 LTS, X64, 4 logical cores", "cases": { "CompileEasy": { - "allocatedBytes": 13826, - "meanNanoseconds": 409149.02092633926 + "allocatedBytes": 15490, + "meanNanoseconds": 411819.7227864583 }, "CompileHard": { - "allocatedBytes": 27888, - "meanNanoseconds": 499996.85323660716 + "allocatedBytes": 31383, + "meanNanoseconds": 511184.2274088542 }, "Derivate": { - "allocatedBytes": 56139, - "meanNanoseconds": 28628.765409197127 + "allocatedBytes": 57227, + "meanNanoseconds": 29320.19936726888 }, "EvalEasy": { "allocatedBytes": 0, - "meanNanoseconds": 3.744399822716202 + "meanNanoseconds": 3.739564356704553 }, "EvalPolynomialFresh": { "allocatedBytes": 12392, - "meanNanoseconds": 8228.309937540691 + "meanNanoseconds": 8231.022261555989 }, "EvalPolynomialFresh15Digits": { "allocatedBytes": 11920, - "meanNanoseconds": 9051.311197553363 + "meanNanoseconds": 9042.05249633789 }, "EvalTranscendentalFresh": { "allocatedBytes": 34640, - "meanNanoseconds": 30436.87562561035 + "meanNanoseconds": 30352.334001813615 }, "EvalTrig": { "allocatedBytes": 69888, - "meanNanoseconds": 59969.564767690805 + "meanNanoseconds": 59684.38562950721 }, "EvalTrigPrecise": { "allocatedBytes": 336498, - "meanNanoseconds": 717843.7869140625 + "meanNanoseconds": 719311.40625 }, "ParseEasy": { - "allocatedBytes": 18386, - "meanNanoseconds": 11232.588527134487 + "allocatedBytes": 18436, + "meanNanoseconds": 10903.259682288537 }, "ParseHard": { - "allocatedBytes": 59751, - "meanNanoseconds": 56299.28791910807 + "allocatedBytes": 59927, + "meanNanoseconds": 53732.40408325195 }, "RunEasy": { "allocatedBytes": 0, - "meanNanoseconds": 48.487677480493275 + "meanNanoseconds": 48.66310466527939 }, "RunHard": { "allocatedBytes": 0, - "meanNanoseconds": 505.936243057251 + "meanNanoseconds": 502.88996543884275 }, "RunMedium": { "allocatedBytes": 0, - "meanNanoseconds": 312.37248986562093 + "meanNanoseconds": 304.26167697906493 }, "SimplifyEasy": { - "allocatedBytes": 79689, - "meanNanoseconds": 87464.0671142578 + "allocatedBytes": 79785, + "meanNanoseconds": 90259.30957500752 }, "SimplifyHard": { - "allocatedBytes": 161716240, - "meanNanoseconds": 175207981.33333334 + "allocatedBytes": 161716160, + "meanNanoseconds": 170258847.5172414 }, "SolveEasy": { - "allocatedBytes": 444247, - "meanNanoseconds": 435638.4725435697 + "allocatedBytes": 443343, + "meanNanoseconds": 456071.09214564733 }, "SolveEasyMedium": { - "allocatedBytes": 66538, - "meanNanoseconds": 38170.384669712614 + "allocatedBytes": 66009, + "meanNanoseconds": 37714.56470133464 }, "SolveHard": { - "allocatedBytes": 9526556, - "meanNanoseconds": 121279380.16666667 + "allocatedBytes": 8514589, + "meanNanoseconds": 110748807.29333334 }, "SolveMedium": { - "allocatedBytes": 459544, - "meanNanoseconds": 528266.8291666667 + "allocatedBytes": 457352, + "meanNanoseconds": 503471.8545735677 }, "SolveMediumHard": { - "allocatedBytes": 1366964, - "meanNanoseconds": 16442697.847916666 + "allocatedBytes": 1346172, + "meanNanoseconds": 14091807.230208334 } }, "ungated": {