diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index c36135e10..626dd888a 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -310,6 +310,42 @@ the candidate ([#2650](https://github.com/asc-community/AngouriMath/issues/2650) | `"(1 - i) + (1 - 2 * i) * (10^30 x) + 2 (10^30 x)^2 - 3 Im(10^30 x) = 0".Solve("x")` | the equation, unsolved | its roots, `10^-30` times those of the equation in `x` | | `"3 + (2 + i) (10^30 x)^2 + 3 Im(10^30 x) = 0".Solve("x")` | the equation, unsolved | its roots, `10^-30` times those of the equation in `x` | +### A root is not accepted on a residual the working digits cannot tell from zero + +**Silent: wrong roots are now no answer.** An equation whose coefficient nearly cancels, such as `P - Q sqrt(2)` with +`P + Q sqrt(2) = (1 + sqrt(2))^n`, was solved with that coefficient read as 0, or past the hundred working digits as +some other number, and the roots were exact numbers that are no roots. The check that puts a root back enclosed its +residual only where the equation had no decimal in it, and an integer of more digits than half the working precision is +parsed as one ([#2615](https://github.com/asc-community/AngouriMath/issues/2615)); and it enclosed to at most the +digits of the largest number once more, where a residual such as `b^2 / 4`, the part of `b^2 + 12` that was dropped, +needs about four times those. A root now leaves the equation unsolved where an interval enclosing its residual leaves +zero out: with such a written integer in it as well, and at digits doubled up to four times the orders the numbers +it is written with span. A polynomial answered with no root is left unsolved where a coefficient read as zero is shown +not to be, and a statement left unsolved keeps its own numbers where simplifying would evaluate one of them to +another ([#2448](https://github.com/asc-community/AngouriMath/issues/2448)). + +`P + Q sqrt(2) = (1 + sqrt(2))^n`, `U - V sqrt(6) = (sqrt(3) - sqrt(2))^n`, `L` and `F` the Lucas and Fibonacci numbers: + +| Input | Was (2.10.0) | Now | +|---|---|---| +| `x^2 + (P - Q sqrt(2)) x - 3`, `n = 160`, `SolveEquation` and `Solve` | `{ (-(P - Q sqrt(2)) - 2 sqrt(3)) / 2, (-(P - Q sqrt(2)) + 2 sqrt(3)) / 2 }`, each leaving `8.1e-124` | the equation, unsolved | +| `x^2 + (1 - sqrt(2))^160 x - 3`, both | the same roots, with `(1 - sqrt(2))^160` for `b` | unsolved | +| `x^2 + (P - Q sqrt(2)) x - 3 = 0`, `n = 270`, `Solve` | `{ x : x ^ 2 + 2499 * x - 3 = 0 }` | `{ x : x ^ 2 + (P - Q * sqrt(2)) * x - 3 = 0 }` | +| `(P - Q sqrt(2)) x - 1`, `n = 200`, both | `{ }` | unsolved | +| `(P - Q sqrt(2)) x - 1 = 0`, `n = 300`, `Solve` | `{ x : 241546412250001 * x - 1 = 0 }` | `{ x : (P - Q * sqrt(2)) * x - 1 = 0 }` | +| `x + (P - Q sqrt(2)) = 0`, `n = 200`, `Solve` | `{ x : x = 0 }` | `{ x : x + P - Q * sqrt(2) = 0 }` | +| `(1 - sqrt(2))^160 x - 1`, both | `{ 17543233911800695450907164956888413406276808032081050028214274 }` | unsolved | +| `x^3 + (P - Q sqrt(2)) x - 1`, `n = 60`, both | `{ }` | unsolved | +| `x^3 + ((L - F sqrt(5)) / 2) x - 1`, `n = 100`, both | `{ }` | unsolved | +| `x^2 + (P - Q sqrt(2)) x - 3`, `n` = 20 to 60, and 220 to 240 through `SolveEquation`; `P + Q sqrt(2)` to 120 | its roots | unchanged | + +Measured against mpmath at 1600 digits for `x^2 + (P -+ Q sqrt(2)) x - 3` at `n` = 20 to 300 by tens, and for +`P - Q sqrt(2)`, `(1 - sqrt(2))^n`, `U - V sqrt(6)` and `(L - F sqrt(5)) / 2` at nine `n` from 20 to 300 in `c x - 1`, +`x + c`, `x^2 + c x - 3`, `x^2 - c`, `c x^2 + x - 1`, `x^3 + c x - 1`, `x^3 - c` and `x^3 + c x^2 - 2 x - 1`, through +`SolveEquation` and `Solve`, a decline counting as one only where its statement is the equation: 674 answers, of which +2.10.0 got 117 wrong and none now; every answer 2.10.0 got right is unchanged. The declines come of downcasting, +which v3 removes. + ### A root of a modulus piece that is not read as a real declines, rather than being left out **Silent: `{ }` becomes the roots.** Over the reals, an equation in moduli of polynomials is solved piece by piece diff --git a/Sources/AngouriMath/Functions/Algebra/Groebner/GroebnerSystemSolver.cs b/Sources/AngouriMath/Functions/Algebra/Groebner/GroebnerSystemSolver.cs index 5df09baff..2e91334a6 100644 --- a/Sources/AngouriMath/Functions/Algebra/Groebner/GroebnerSystemSolver.cs +++ b/Sources/AngouriMath/Functions/Algebra/Groebner/GroebnerSystemSolver.cs @@ -204,7 +204,12 @@ static bool BackSubstitute( if (univariate is null) return budget.Allow(false, "no univariate equation"); - if (univariate.SolveEquation(variable).InnerSimplified is not Set.FiniteSet roots) + Entity solved; + // Each root is put back into the system below, so it is not enclosed to more digits here as well. + // https://github.com/asc-community/AngouriMath/issues/2448 + using (AnalyticalSolving.StatementSolver.WithoutRisingDigits()) + solved = univariate.SolveEquation(variable).InnerSimplified; + if (solved is not Set.FiniteSet roots) return budget.Allow(false, "unenumerable roots"); var remaining = new Dictionary(at); diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs index 2c329e50e..df9698c17 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/SolveStatement.cs @@ -50,6 +50,13 @@ internal static Set WithoutSpuriousRoots(Set roots, Entity equation, Variable x) { if (roots is not FiniteSet finite) return roots; + // No root at all is a claim too, and a polynomial of degree one or more has one. A coefficient + // that downcasting took for zero takes the degree with it, or the formula's branch: with + // (1 + sqrt(2))^n = P + Q sqrt(2), (P - Q sqrt(2)) x - 1 at n = 200 and x^3 + (P - Q sqrt(2)) x - 1 + // at n = 60 were answered { }. + // https://github.com/asc-community/AngouriMath/issues/2448 + if (finite.Count == 0) + return HasADegreeTakenForZero(equation, x) ? Unsolved(equation, x) : roots; List? survivors = null; var index = 0; foreach (var root in finite) @@ -101,6 +108,45 @@ private static bool IsAPolynomialWithARoot(Entity equation, Variable x) .Any(monomial => monomial.Value.Evaled is Number.Complex { IsZero: false }) && monomials.Values.All(coefficient => coefficient.Evaled is Number.Complex { IsFinite: true }); + /// + /// Whether is, as written, a polynomial in with + /// numbers for coefficients, of which one at a power of one or more is not zero, by its value or, + /// where downcasting reads it as zero, by an interval: a polynomial with a root over the complex + /// numbers, which an answer of none denies. + /// + /// + /// As written, since simplifying it folds the coefficient the same way: (P - Q sqrt(2)) x - 1 + /// with (1 + sqrt(2))^200 = P + Q sqrt(2) simplifies to -1. And made of sums, + /// products and whole positive powers of alone, with no condition, so that no + /// root of the polynomial is one the equation excludes: x^0 x = 0 reads as x, and + /// has no root, since 0^0 has no value. + /// https://github.com/asc-community/AngouriMath/issues/2448 + /// + private static bool HasADegreeTakenForZero(Entity equation, Variable x) + => MathS.Settings.Codomain.Value != Core.Domain.Real + && IsPolynomialArithmetic(equation, x) + && TreeAnalyzer.TryGetPolynomial(equation, x, out var monomials) + && monomials.Keys.All(power => power.Sign >= 0) + && monomials.Values.All(coefficient => coefficient.Evaled is Number.Complex { IsFinite: true }) + && monomials.Any(monomial => monomial.Key.Sign > 0 && !monomial.Value.Vars.Any() + && (monomial.Value.Evaled is Number.Complex { IsZero: false } || IsShownNotZeroAsTheDigitsRise(monomial.Value))); + + /// + /// Whether is sums, differences and products of + /// raised to whole positive powers and of expressions free of it, which have no symbol in them. + /// + private static bool IsPolynomialArithmetic(Entity expression, Variable x) + => expression switch + { + _ when !expression.ContainsNode(x) => !expression.Vars.Any(), + Variable => true, + Sumf(var a, var b) => IsPolynomialArithmetic(a, x) && IsPolynomialArithmetic(b, x), + Minusf(var a, var b) => IsPolynomialArithmetic(a, x) && IsPolynomialArithmetic(b, x), + Mulf(var a, var b) => IsPolynomialArithmetic(a, x) && IsPolynomialArithmetic(b, x), + Powf(var @base, Integer { EInteger: var power }) when power.Sign > 0 => IsPolynomialArithmetic(@base, x), + _ => false, + }; + /// /// Answers the condition itself where a root denies the independence the calculus /// operators in the equation were evaluated under. @@ -235,11 +281,121 @@ private static RootVerdict Verdict(Entity equation, Variable x, Entity root) } if (!IsExact(root) && IsLargeBesideTheTermsAsWritten(equation, x, root, substituted)) return RootVerdict.Spurious; - return !substituted.Vars.Any() && IsAboveTheIntervalFloor(equation, x, root) && IsShownNotZero(substituted) + if (substituted.Vars.Any()) + return RootVerdict.Kept; + // A fresh tree, since the residual is evaluated below without downcasting, and a tree that + // was evaluated with it keeps what it was evaluated to wherever the settings come back. + var afresh = equation.Substitute(x, root); + var size = SizeOf(afresh); + if (size.HasAWorkedOutDecimal) + return RootVerdict.Kept; + // The digits rise only for a polynomial as written, whose roots are worked out by formulas that a + // coefficient downcasting read as zero or as another number leads astray, and whose residual a + // true root keeps at zero to every digit. An equation with sgn or abs in it is solved by pieces + // whose roots are put back as they are found, and enclosed again here to hundreds of digits each, + // -1 - i + i x + (-1 + (2 + i) x) sgn(3x - 2) = 0 with x written 10^-30 x took twice as long. + // https://github.com/asc-community/AngouriMath/issues/2448 + return IsAboveTheIntervalFloor(afresh, size.MostDigits) && IsShownNotZero(substituted) + || IsPolynomialArithmetic(equation, x) && IsShownNotZeroAsTheDigitsRise(substituted, size.WrittenDigits, size.Reach) ? RootVerdict.ShownNotARoot : RootVerdict.Kept; } + /// + /// Whether has a decimal in it that was worked out, as + /// tells one from an integer written with more digits than + /// downcasting reads; the most digits of a number in it, by ; and the span + /// of the sizes of the numbers it is written with, in decimal orders: how many the largest is above + /// one and the smallest below it, added, a number raised to a whole power past + /// counted as the power of its size; and from those, the digits past the + /// working ones a residual with them in may take to tell from zero. + /// + /// + /// That reach is twice the orders above one and twice the more of those below one and those above: + /// a quadratic's terms have twice the orders of its numbers, and what it leaves can be as small as the + /// square of the smallest number in it, which a difference of numbers s orders above one makes as + /// small as 10^-s, as P - Q sqrt(2) = 1 / (P + Q sqrt(2)) is. With + /// (1 + sqrt(2))^160 = P + Q sqrt(2), near 10^61, that is 246 digits. It is the cost of + /// every true root whose numbers are large or small, whose enclosure holds zero at every step: four + /// times the span, the exact roots of -1 - i + i x + (-1 + (2 + i) x) sgn(3x - 2) = 0 with + /// x written 10^-30 x, whose numbers span 190 orders, were enclosed to 860 digits, and the + /// solve took three times as long. + /// + private static (bool HasAWorkedOutDecimal, int MostDigits, int WrittenDigits, int Reach) SizeOf(Entity expression) + { + var hasADecimal = false; + var mostDigits = 0; + long above = 0, below = 0; + foreach (var node in expression.Nodes) + switch (node) + { + case Complex number: + hasADecimal |= !IsAWrittenInteger(number.RealPart) || !IsAWrittenInteger(number.ImaginaryPart); + mostDigits = System.Math.Max(mostDigits, System.Math.Max(DigitCount(number.RealPart), DigitCount(number.ImaginaryPart))); + foreach (var part in new[] { number.RealPart, number.ImaginaryPart }) + if (OrderOf(part) is { } order) + (above, below) = (System.Math.Max(above, order + 1), System.Math.Max(below, -order)); + break; + case Powf(var @base, Integer power) when power.EInteger.Abs().CompareTo(FewWrittenDigits) > 0 && !@base.Vars.Any() + && power.EInteger.CanFitInInt32() + && @base.Evaled is Complex value && OrderOf(value.Abs()) is { } baseOrder: + // |base|^k is within k orders of 10^(k e), e the order of the base. + var k = (long)power.EInteger.ToInt32Unchecked(); + var orders = System.Math.Abs(k) * System.Math.Max(System.Math.Abs(baseOrder), System.Math.Abs(baseOrder + 1)); + if (baseOrder >= 0 == k > 0) + above = System.Math.Max(above, orders); + else + below = System.Math.Max(below, orders); + break; + } + var span = above + below; + var reach = 2 * (above + System.Math.Max(above, below)); + return (hasADecimal, mostDigits, span > int.MaxValue ? int.MaxValue : (int)span, reach > int.MaxValue ? int.MaxValue : (int)reach); + + // The decimal order of a part: e with 10^e <= |part| < 10^(e + 1), null for zero or no number. + static long? OrderOf(Real part) + { + if (part is Rational rational) + { + if (rational.ERational.IsZero) + return null; + var order = rational.ERational.Numerator.Abs().GetDigitCountAsEInteger().Subtract(rational.ERational.Denominator.GetDigitCountAsEInteger()); + return order.CanFitInInt32() ? order.ToInt32Unchecked() : null; + } + if (!part.EDecimal.IsFinite || part.EDecimal.IsZero) + return null; + var adjusted = part.EDecimal.Exponent.Add(part.EDecimal.UnsignedMantissa.GetDigitCountAsEInteger()).Subtract(1); + return adjusted.CanFitInInt32() ? adjusted.ToInt32Unchecked() : null; + } + } + + /// + /// Whether is exact, or a decimal holding an integer digit for digit, with no + /// exponent: the integer as it was written. + /// + /// + /// An integer of more digits than half the working precision is parsed as a decimal, since + /// evaluation cannot round it onto an integer (https://github.com/asc-community/AngouriMath/issues/2615), + /// so an equation with (1 + sqrt(2))^160 = P + Q sqrt(2) in it has P and Q as + /// decimals, and its roots, (-(P - Q sqrt(2)) +- 2 sqrt(3)) / 2 with b^2 + 12 read as + /// 12, were never enclosed. Such a decimal is the number it says, and a residual with it is + /// enclosed as that number. One a solver worked out is not: rounded, it has the working digits, or a + /// part below its point, and a root of an equation with it in is only as accurate as it. The roots of + /// the univariate equations a Groebner basis is solved through have the decimals of the roots already + /// put in, and enclosed exactly, each of those was a residual the rounding left and none the solve + /// did: -3 - x + 3 x^2 - 3 sgn(-x) - 3 Im(x) = 0 with x written 10^12 x was left + /// unsolved. + /// #2448 + /// + private static bool IsAWrittenInteger(Real part) + { + if (part is Rational) + return true; + // An integer parsed is held digit for digit, with no exponent; a number worked out is rounded to + // the working digits, which below one leaves it a part below its point and above them an exponent. + return part.EDecimal.IsFinite && part.EDecimal.Exponent.IsZero; + } + /// What does with a root. private enum RootVerdict { @@ -334,9 +490,9 @@ private static int IntervalDigits() } /// - /// 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 . + /// Whether , a residual in a tree of its own whose largest number has + /// digits, evaluated without downcasting, is further from zero than + /// rounding leaves of a true root's: only such a residual is enclosed by . /// /// /// @@ -354,22 +510,8 @@ private static int IntervalDigits() /// P near 1.9e53, which takes 108 digits to tell from zero. /// /// - private static bool IsAboveTheIntervalFloor(Entity equation, Variable x, Entity root) + private static bool IsAboveTheIntervalFloor(Entity substituted, int mostDigits) { - var substituted = equation.Substitute(x, root); - 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)) @@ -383,15 +525,120 @@ private static bool IsAboveTheIntervalFloor(Entity equation, Variable x, Entity 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(), + /// + /// The decimal digits is written with: those of the numerator or the + /// denominator of a rational, and of a decimal the digits of its mantissa or the places from + /// its point to its first digit, whichever are more. + /// + private static int DigitCount(Real part) + { + EInteger count; + if (part is Rational rational) + count = EInteger.Max(rational.ERational.Numerator.Abs().GetDigitCountAsEInteger(), rational.ERational.Denominator.GetDigitCountAsEInteger()); - return count.CanFitInInt32() ? count.ToInt32Unchecked() : int.MaxValue; + else if (part.EDecimal.IsFinite && !part.EDecimal.IsZero) + { + var value = part.EDecimal; + var mantissa = value.UnsignedMantissa.GetDigitCountAsEInteger(); + count = EInteger.Max(mantissa, value.Exponent.Add(mantissa).Abs()); + } + else + return 0; + return count.CanFitInInt32() ? count.ToInt32Unchecked() : int.MaxValue; + } + + /// + /// Whether an interval enclosing , a number with no symbol in it, + /// leaves out zero at some number of digits up to the reach works out from the + /// numbers it is written with, beyond those start from; never where + /// a decimal in it was worked out, which is only as accurate as what worked it out. + /// + /// + /// + /// What rounding leaves of a root's residual is no smaller in absolute terms than the + /// digits the evaluation drops, and those are the size of the terms beyond the working + /// precision; what a root the solve got wrong leaves can be smaller than either, since it is + /// the size of whatever the downcasting took for zero. gives the + /// terms their digits once, which is not enough where the residual is smaller than the + /// rounding of the terms: with (1 + sqrt(2))^160 = P + Q sqrt(2) and + /// b = P - Q sqrt(2), near 1.1e-61, the roots of x^2 + b x - 3 were + /// answered with b^2 + 12 read as 12, and leave b^2 / 4, about + /// 8.1e-124, against terms near 1.9e123: 246 digits tell it from zero, and the + /// enclosure stopped at 224. + /// + /// + /// So the digits are doubled until the enclosure leaves zero out, as far as a bound set by the + /// orders the numbers in the tree span, written or raised to an integer power: a residual built + /// from numbers within s orders of one in a polynomial of low degree is a nonzero + /// algebraic number whose size, and whose terms', are within a few times s orders of + /// one. A true root's enclosure holds zero at every step, so the bound is what such a root + /// costs, and it is met only where the numbers are large or small: where they span + /// orders or fewer, nothing is evaluated here. + /// #2448, + /// #1019 + /// + /// + internal static bool IsShownNotZeroAsTheDigitsRise(Entity residual) + => SizeOf(residual) is { HasAWorkedOutDecimal: false } size && IsShownNotZeroAsTheDigitsRise(residual, size.WrittenDigits, size.Reach); + + /// + /// , with the orders the + /// numbers is written with span and the digits past + /// the working ones to enclose it to at most, as works them out. + /// + private static bool IsShownNotZeroAsTheDigitsRise(Entity residual, int size, int reach) + { + if (size <= FewWrittenDigits || risingDigitsOff > 0) + return false; + var start = IntervalDigits(); + var most = start + System.Math.Min(reach, MostRisenDigits); + for (var digits = start + size; ; digits = System.Math.Min(2 * digits, most)) + { + if (Numerics.PreciseEvaluation.Of(residual, digits) is { } enclosure + && (enclosure.Re.Mignitude.Sign > 0 || enclosure.Im.Mignitude.Sign > 0)) + return true; + if (digits >= most) + return false; } } + [System.ThreadStatic] private static int risingDigitsOff; + + /// + /// A scope in which encloses nothing, for a solve + /// whose roots are checked against equations of the caller's afterwards: the univariate equations a + /// Groebner basis is solved through are made by elimination, and each root of one is put back into + /// the system. Enclosed there, every exact root of those equations, true ones included, was taken + /// to hundreds of digits, which made -1 - i + i x + (-1 + (2 + i) x) sgn(3x - 2) = 0 with + /// x written 10^-30 x eight times slower. A thread-static count, so a solve the scope + /// covers is synchronous. + /// #2448 + /// + internal static RisingDigitsOff WithoutRisingDigits() + { + risingDigitsOff++; + return default; + } + + /// Closes . + internal readonly struct RisingDigitsOff : System.IDisposable + { + public void Dispose() => risingDigitsOff--; + } + + /// + /// The orders the numbers in a residual span, up to which + /// leaves it to : what rounding leaves of terms near one. + /// + private const int FewWrittenDigits = 10; + + /// + /// The most digits adds, which bounds what one root costs. + /// + private const int MostRisenDigits = 4000; + /// /// How many of rounding takes from a true root's residual, /// by : the roots of x^2 + 3x - 5 leave @@ -942,7 +1189,61 @@ private static Entity Equivalent(Entity left, Entity right) /// callers read it as not solved. https://github.com/asc-community/AngouriMath/issues/1540 /// internal static Set? Solved(Entity statement, Variable x) - => Solve(statement, x)?.InnerSimplified as Set; + { + if (Solve(statement, x) is not { } solved) + return null; + // A statement left unsolved is kept as it was written where its numbers are large or decimals: + // simplifying it evaluates them, and where they cancel past the working digits it rounds the + // statement into another. (P - Q sqrt(2)) x - 1 = 0, with (1 + sqrt(2))^300 = P + Q sqrt(2), + // was declined and then simplified into { x : -758453587749999 x - 1 = 0 }, which names another + // number, and at the 200th power into { }, which says there is none. + // https://github.com/asc-community/AngouriMath/issues/2448 + if (solved is ConditionalSet { Predicate: var predicate } && predicate == statement + && SizeOf(statement) is var size && !size.HasAWorkedOutDecimal && size.WrittenDigits > FewWrittenDigits + && HasAConstantTheDigitsMisread(statement)) + return solved; + return solved.InnerSimplified as Set; + } + + /// + /// Whether has a part with no symbol in it, a sum or a difference, that + /// the working digits evaluate to something else than it is: an interval enclosing it, to as many + /// more digits as it takes, leaves zero out and is not near what it evaluates to. Simplifying such an + /// expression puts that value in its place. 10^12 x has none; (P - Q sqrt(2)) x - 1, + /// with (1 + sqrt(2))^300 = P + Q sqrt(2), evaluates P - Q sqrt(2) to + /// 241546412250001. + /// + private static bool HasAConstantTheDigitsMisread(Entity expression) + { + switch (expression) + { + case Sumf or Minusf when !expression.Vars.Any(): + if (expression.Evaled is not Complex value) + return false; + var size = SizeOf(expression).WrittenDigits; + var digits = IntervalDigits() + (int)System.Math.Min((long)size * 2, MostRisenDigits); + if (Numerics.PreciseEvaluation.Of(expression, digits) is not { } enclosure + || enclosure.Re.Mignitude.Sign <= 0 && enclosure.Im.Mignitude.Sign <= 0) + return false; + var near = EDecimal.Max(enclosure.Re.Magnitude, enclosure.Im.Magnitude).Multiply(MisreadShare); + return !(IsNear(value.RealPart.EDecimal, enclosure.Re) && IsNear(value.ImaginaryPart.EDecimal, enclosure.Im)); + + bool IsNear(EDecimal decimalValue, Numerics.PreciseInterval interval) + => decimalValue.Subtract(interval.High).CompareTo(near) <= 0 && interval.Low.Subtract(decimalValue).CompareTo(near) <= 0; + default: + foreach (var child in expression.DirectChildren) + if (HasAConstantTheDigitsMisread(child)) + return true; + return false; + } + } + + /// + /// How far from its enclosure, as a share of the enclosure's size, the value a constant evaluates to is + /// read as another number by : further than rounding to a + /// hundred digits puts it, and nearer than any number it was mistaken for. + /// + [ConstantField] private static readonly EDecimal MisreadShare = EDecimal.FromString("1E-20"); /// /// An abs(u) in with in it and no diff --git a/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs b/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs index 066555a37..b0b48521f 100644 --- a/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs @@ -380,6 +380,127 @@ public void Issue2448_EveryRootOfAQuadraticWithACancellingCoefficientIsARoot(int } } + // The same coefficient past the hundred digits evaluation works to, and others like it: (1 - sqrt(2))^n + // written as it is, U - V sqrt(6) = (sqrt(3) - sqrt(2))^(2m), and (L - F sqrt(5)) / 2 = phi'^n with L and F + // the Lucas and Fibonacci numbers. Downcasting read the coefficient as 0, or past the digits as some + // other number, and the answers were exact numbers that are no roots: { 0 } for x + c, { } for + // c x - 1 and for x^3 + c x - 1, and at n = 160 the roots of x^2 + c x - 3 written with b^2 + 12 read + // as 12, which leave about 8.1e-124. An integer of more digits than half the working precision is + // parsed as a decimal (https://github.com/asc-community/AngouriMath/issues/2615), so the coefficient + // is asked both as parsed and built from Integers. Each answer is either the roots, every one of + // them, each enclosed within 1e-1000 of zero at 2000 digits, or the equation left unsolved with its + // own numbers in it: simplifying a declined statement with these numbers rounded it into another, + // { x : -758453587749999 x - 1 = 0 }, or into { }. The declines come of downcasting, which v3 removes: + // https://github.com/asc-community/AngouriMath/issues/1019#issuecomment-5754734225 + // https://github.com/asc-community/AngouriMath/issues/2448 + [Theory] + [InlineData("x^2 + c * x - 3", "pell", 130)] + [InlineData("x^2 + c * x - 3", "pell", 160)] + [InlineData("x^2 + c * x - 3", "pell", 270)] + [InlineData("x^2 + c * x - 3", "pell", 300)] + [InlineData("x^2 + c * x - 3", "pell-integers", 160)] + [InlineData("x^2 + c * x - 3", "raw", 160)] + [InlineData("x^2 + c * x - 3", "s6", 100)] + [InlineData("x^2 + c * x - 3", "phi", 300)] + [InlineData("c * x - 1", "pell", 160)] + [InlineData("c * x - 1", "pell", 200)] + [InlineData("c * x - 1", "pell", 300)] + [InlineData("c * x - 1", "raw", 160)] + [InlineData("c * x - 1", "s6", 120)] + [InlineData("c * x - 1", "phi", 300)] + [InlineData("x + c", "pell", 200)] + [InlineData("x + c", "s6", 120)] + [InlineData("x^2 - c", "phi", 300)] + [InlineData("c * x^2 + x - 1", "pell", 200)] + [InlineData("x^3 + c * x - 1", "pell", 60)] + [InlineData("x^3 + c * x - 1", "s6", 40)] + [InlineData("x^3 + c * x - 1", "phi", 100)] + [InlineData("x^3 + c * x - 1", "raw", 60)] + [InlineData("x^3 - c", "pell", 200)] + [InlineData("x^3 + c * x^2 - 2 * x - 1", "pell", 160)] + [InlineData("x^3 + c * x^2 - 2 * x - 1", "raw", 300)] + public void Issue2448_ARootOfANearlyCancellingCoefficientIsARootOrTheEquationIsLeftUnsolved(string template, string family, int n) + { + var c = NearlyCancelling(family, n); + var equation = template.ToEntity().Substitute("c", c); + var degree = template.Contains("x^3") ? 3 : template.Contains("x^2") ? 2 : 1; + foreach (var solutions in new[] { MathS.SolveEquation(equation, "x"), equation.Equalizes(0).Solve("x") }) + { + if (solutions is Entity.Set.ConditionalSet { Predicate: Entity.Equalsf(var left, var right) }) + { + // Left unsolved: the statement is this equation, with no number in it the equation was not written with. + var written = equation.Nodes.OfType().Select(number => number.Abs()).ToHashSet(); + foreach (var number in (left - right).Nodes.OfType()) + Assert.True(number.IsZero || written.Contains(number.Abs()), $"{solutions} has {number} in it, which {equation} has not"); + foreach (var large in written.Where(number => number.EDecimal.Abs().CompareTo(PeterO.Numbers.EDecimal.FromString("1E12")) > 0)) + Assert.True((left - right).Nodes.OfType().Any(number => number.Abs() == large), $"{solutions} has lost {large}"); + continue; + } + var roots = Assert.IsType(solutions); + Assert.Equal(degree, roots.Count); + foreach (var root in roots) + { + var residual = equation.Substitute("x", root); + var enclosure = AngouriMath.Numerics.PreciseEvaluation.Of(residual, 2000); + Assert.True(enclosure is { } value + && value.Re.Magnitude.CompareTo(PeterO.Numbers.EDecimal.FromString("1E-1000")) <= 0 + && value.Im.Magnitude.CompareTo(PeterO.Numbers.EDecimal.FromString("1E-1000")) <= 0, + $"{root} is no root of {equation}"); + } + } + + static Entity NearlyCancelling(string family, int n) + { + System.Numerics.BigInteger a = 1, b = 0; + switch (family) + { + case "pell" or "pell-integers": + for (var i = 0; i < n; i++) + (a, b) = (a + 2 * b, a + b); + return family == "pell" + ? $"({a} - {b} * sqrt(2))".ToEntity() + : Entity.Number.Integer.Create(PeterO.Numbers.EInteger.FromString(a.ToString())) - Entity.Number.Integer.Create(PeterO.Numbers.EInteger.FromString(b.ToString())) * MathS.Sqrt(2); + case "raw": + return $"(1 - sqrt(2))^{n}".ToEntity(); + case "s6": + for (var i = 0; i < n / 2; i++) + (a, b) = (5 * a + 12 * b, 2 * a + 5 * b); + return $"({a} - {b} * sqrt(6))".ToEntity(); + default: + System.Numerics.BigInteger f = 0, next = 1; + for (var i = 0; i < n; i++) + (f, next) = (next, f + next); + return $"({2 * next - f}/2 - {f}/2 * sqrt(5))".ToEntity(); + } + } + } + + // The check above encloses a residual only with exact numbers in it, or an integer written with more + // digits than downcasting reads. A decimal a solver worked out is not one: the univariate equations a + // Groebner basis is solved through have decimal roots of the others put in, and each of their roots, + // enclosed exactly, left what the rounding did, so these were left unsolved. Each has its roots, or + // none, at every scale of x, as unscaled; the second has none, sgn(3x^2 + 3x - 1) being a unit that + // the equation's linear part in x cannot meet. https://github.com/asc-community/AngouriMath/issues/2448 + [Theory] + [InlineData("-3 - x + 3x^2 - 3 sgn(-x) - 3 Im(x) = 0", "6", "1/3", "(1 - sqrt(73)) / 6")] + [InlineData("-3 - x + 3x^2 - 3 sgn(-x) - 3 Im(x) = 0", "12", "1/3", "(1 - sqrt(73)) / 6")] + [InlineData("-3 - x + 3x^2 - 3 sgn(-x) - 3 Im(x) = 0", "30", "1/3", "(1 - sqrt(73)) / 6")] + [InlineData("-2 + (3 - i) x + (2 + i) sgn(3x^2 + 3x - 1) - 2 Im(x) = 0", "12")] + [InlineData("-2 + (3 - i) x + (2 + i) sgn(3x^2 + 3x - 1) - 2 Im(x) = 0", "30")] + public void Issue2448_AnEquationInTheComplexPartsOfXIsSolvedAtEveryScaleOfX(string equation, string power, params string[] roots) + { + var scaled = equation.ToEntity().Substitute("x", $"10^{power} * x".ToEntity()); + var answer = Assert.IsType(scaled.Solve("x")); + Assert.Equal(roots.Length, answer.Count); + foreach (var root in roots) + { + var expected = ($"({root}) / 10^{power}").ToEntity(); + Assert.Contains(answer, found => AngouriMath.Numerics.PreciseEvaluation.Of(found - expected, 200) is { } difference + && difference.Re.Magnitude.CompareTo(PeterO.Numbers.EDecimal.FromString($"1E-{int.Parse(power) + 60}")) <= 0 + && difference.Im.Magnitude.CompareTo(PeterO.Numbers.EDecimal.FromString($"1E-{int.Parse(power) + 60}")) <= 0); + } + } + // A family met with a set of reals is its real members: an exponential's family over the complex // numbers, c + k n with c real and k imaginary, is real at n = 0 alone, and a trigonometric one has // the members between the interval's ends. The first two were answered so before the families