diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 141bf3467..c12e79371 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -179,6 +179,29 @@ 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 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 +between the kinks, and a root of a piece was kept only where it evaluated to a real inside the piece. Any other root +was left out as though it were known to be complex or outside. With `x` written `10^30 x` the decimals flushed the +parts of the quartic's roots, near `10^-31`, and read them as complex numbers near `2.27`, so all eight were left +out and the equation was answered `{ }`. A root is now left out only where it is decided to be non-real, by an +enclosure off the real line or by an imaginary part clear of the rounding of the roots' size. It is left out of a +piece only where it is decided to be outside it, exactly for rationals and otherwise by enclosures that are apart. +Every reading is taken without the exponent floor, and a root decided neither way declines the equation +([#2659](https://github.com/asc-community/AngouriMath/issues/2659)). + +Measured over 298 equations in moduli with `x` written `10^30 x` or `x / 10^30`, codomain `Real`, on `97f26c663` +and on this branch: 16 answers changed and none became a decline. Each new answer is the unscaled equation's real +roots, scaled. 13 of the old ones lacked roots, and 3 were the same roots written another way. + +| `.SolveEquation("x")`, codomain `Real` | Was (`97f26c663`) | Now | +|---|---|---| +| `(10^30 x)^4 - 10 (10^30 x)^2 + abs(10^30 x) + 1` | `{ }` | its four real roots, `10^-30` times those of `x^4 - 10 x^2 + abs(x) + 1` | +| `-2 + 3 (x/10^30)^3 + 3 abs(-1 + x/10^30)` | one root, near `-1.137 10^30` | three, near `-1.137`, `0.395` and `0.742` times `10^30` | +| `1 + (-2) (10^30 x) - 2 (10^30 x)^2 - 3 (10^30 x)^3 + 2 (10^30 x)^4 - 3 abs(3 (10^30 x))` | three roots | four: the one near `0.0893 10^-30` was missing | +| `3 (x/10^30) - 2 (x/10^30)^2 + 3 (x/10^30)^3 + 2 abs(1 - 2 (x/10^30) - 3 (x/10^30)^2)` | `{ }` | `{ }` was wrong: its root near `-0.513 10^30` | + ### The whole part of a large rational power is taken out **Silent, in the printed form only.** A rational raised to a rational power was written as a whole part times a diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs index b9d85b892..20e97bfe2 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Linq; +using PeterO.Numbers; using static AngouriMath.Entity; using static AngouriMath.Entity.Number; using static AngouriMath.Entity.Set; @@ -110,7 +111,7 @@ private static bool RealWhereverItIs(Entity expr, Variable x) internal static Set? SolveOverTheReals(Entity expr, Variable x) { var moduli = new List(); - var kinks = new List<(Entity Exact, Real Value)>(); + var kinks = new List(); foreach (var node in expr.Nodes) { if (node is not Absf(var argument) || !argument.ContainsNode(x)) @@ -122,34 +123,54 @@ private static bool RealWhereverItIs(Entity expr, Variable x) } if (moduli.Count == 0) return null; - var ends = kinks.GroupBy(kink => kink.Value).Select(same => same.First()) - .OrderBy(kink => kink.Value.EDecimal).Select(kink => kink.Exact).ToList(); + // In order, a kink that is another's point once; two whose order is not decided decline. + kinks.Sort(static (left, right) => left.Value.EDecimal.CompareTo(right.Value.EDecimal)); + var ends = new List(); + foreach (var kink in kinks) + { + if (ends.Count > 0) + { + var order = Compare(ends[^1], kink); + if (order is not { } sign || sign > 0) + return null; + if (sign == 0) + continue; + } + ends.Add(kink); + } // The pieces between neighbouring kinks, closed where they end at one, and on each the // sign every modulus takes, read at a point inside it. Set answer = Set.Empty; for (var i = 0; i <= ends.Count; i++) { - Entity left = i == 0 ? Real.NegativeInfinity : ends[i - 1]; - Entity right = i == ends.Count ? Real.PositiveInfinity : ends[i]; + Point? left = i == 0 ? null : ends[i - 1]; + Point? right = i == ends.Count ? null : ends[i]; Entity inside = ends.Count == 0 ? Integer.Zero - : i == 0 ? ends[0] - 1 : i == ends.Count ? ends[^1] + 1 : (ends[i - 1] + ends[i]) / 2; + : i == 0 ? ends[0].Exact - 1 : i == ends.Count ? ends[^1].Exact + 1 : (ends[i - 1].Exact + ends[i].Exact) / 2; var signs = new Dictionary(); foreach (var argument in moduli) if (!signs.ContainsKey(argument)) { - if (argument.Substitute(x, inside).Evaled is not Real value) + // Not zero inside a piece, which no kink is in; read as 0, it is undecided. + if (SignOf(argument.Substitute(x, inside)) is not { } sign || sign == 0) return null; - signs[argument] = !value.IsNegative; + signs[argument] = sign > 0; } var withoutModuli = expr.Replace(node => node is Absf(var argument) && signs.TryGetValue(argument, out var nonNegative) ? (nonNegative ? argument : -argument) : node).InnerSimplified; - Set piece = new Interval(left, i > 0, right, i < ends.Count); + Set piece = new Interval(left?.Exact ?? Real.NegativeInfinity, left is not null, right?.Exact ?? Real.PositiveInfinity, right is not null); if (!withoutModuli.ContainsNode(x)) { - if (withoutModuli.Evaled is Complex { IsZero: true }) - answer = answer.Unite(piece); + switch (IsZero(withoutModuli)) + { + case null: + return null; + case true: + answer = answer.Unite(piece); + break; + } continue; } var solved = AnalyticalEquationSolver.Solve(withoutModuli, x); @@ -163,9 +184,30 @@ private static bool RealWhereverItIs(Entity expr, Variable x) } if (solved is not FiniteSet roots) return null; - foreach (var root in roots) - if (root.Evaled is Real value && Within(value, left, right)) - answer = answer.Unite(new FiniteSet(root)); + // A root is left out only where it is decided not to be real, or decided to be outside + // the piece. One read as neither was left out too, and the equation answered { }: with x + // written 10^30 x, the decimals flushed the parts of the quartic's roots, near 10^-31, + // and read them as complex numbers near 2.27. https://github.com/asc-community/AngouriMath/issues/2659 + if (ReadAll(roots) is not { } read) + return null; + foreach (var root in read) + { + if (root is null) + continue; + // A rational root the piece's equation is decided not to hold at stands in for a root + // that is missing, which the answer would be without: x^4 - 10 x^2 + x + 10^(-150) had + // 0 for its root near -10^(-150). + if (root.Exact is Rational && withoutModuli.Substitute(x, root.Exact).InnerSimplified is Rational { ERational.IsZero: false }) + return null; + switch (Within(root, left, right)) + { + case null: + return null; + case true: + answer = answer.Unite(new FiniteSet(root.Exact)); + break; + } + } } return (Set)answer.InnerSimplified; } @@ -173,14 +215,14 @@ private static bool RealWhereverItIs(Entity expr, Variable x) /// /// The real roots of , exact and with their values, where it is a /// polynomial in with real numeric coefficients whose roots the solver - /// finds; otherwise. + /// finds and each is decided real or not; otherwise. /// - private static List<(Entity Exact, Real Value)>? RealRootsOf(Entity argument, Variable x) + private static List? RealRootsOf(Entity argument, Variable x) { if (TreeAnalyzer.TryGetPolyLinear(argument, x, out var slope, out var intercept)) return !intercept.ContainsNode(x) && slope.Evaled is Real { IsZero: false } && (-intercept / slope).InnerSimplified is Real kink - ? new() { (kink, kink) } + ? new() { new(kink, kink) } : null; if (!TreeAnalyzer.TryGetPolynomial(argument, x, out var monomials) || monomials.Count == 0 @@ -189,23 +231,203 @@ private static bool RealWhereverItIs(Entity expr, Variable x) return null; if (AnalyticalEquationSolver.Solve(argument, x) is not FiniteSet roots) return null; - var real = new List<(Entity, Real)>(); - foreach (var root in roots) - switch (root.Evaled) + // A kink left out is two pieces read as one, with the sign of a modulus wrong on part of it. + if (ReadAll(roots) is not { } read) + return null; + var real = new List(); + foreach (var root in read) + if (root is not null) + real.Add(root); + return real; + } + + /// + /// A real number, as it is written and as it evaluates without the exponent floor. + /// + private sealed class Point + { + internal Point(Entity exact, Real value, EDecimal? scale = null) + { + Exact = exact; + Value = value; + Scale = scale ?? value.EDecimal.Abs(); + } + + internal Entity Exact { get; } + + internal Real Value { get; } + + /// + /// The size the rounding of is beside: the largest of the roots it was + /// found with, which a formula computes it from. A root near 10^-150 beside roots near 3 is + /// what is left of terms near 3 cancelling, and its last hundred digits are rounding. + /// + internal EDecimal Scale { get; } + + private Numerics.PreciseComplexInterval? enclosure; + private int digits; + + /// + /// An enclosure of the exact value in digits, or null where the + /// interval evaluator finds none, as at a cut its interval straddles. + /// + internal Numerics.PreciseComplexInterval? Enclosure(int precision) + { + if (digits != precision) { - case Real value: - real.Add((root, value)); - break; - case Complex { ImaginaryPart.IsZero: true } value: - real.Add((root, value.RealPart)); - break; + enclosure = Numerics.PreciseEvaluation.Of(Exact, precision); + digits = precision; } - return real; + return enclosure; + } } - private static bool Within(Real value, Entity left, Entity right) - => left.Evaled is Real low && right.Evaled is Real high - && low.EDecimal.CompareTo(value.EDecimal) <= 0 && value.EDecimal.CompareTo(high.EDecimal) <= 0; + /// The digits an enclosure is computed in, in turn, until it decides. + [AngouriMath.Core.ConstantField] + private static readonly int[] EnclosureDigits = { 40, 80 }; + + /// + /// Each of as a real , or null where it is decided + /// not to be real; where one of them is neither. + /// + /// + /// Not real where an enclosure of it is off the real line. Real where it evaluates, without the + /// exponent floor, to a real number, or to one whose imaginary part is the rounding of the + /// roots' size; and, where no enclosure is found, not real where its imaginary part is clear of + /// that rounding. The last two read decimals: a temporary reading before v3, which decides it + /// exactly. https://github.com/asc-community/AngouriMath/issues/1019#issuecomment-5754734225 + /// + private static List? ReadAll(FiniteSet roots) + { + var values = new List<(Entity Root, Complex Value)>(); + using (MathS.Settings.DecimalPrecisionContext.Set(InternalAMExtensions.WithUnboundedExponents(MathS.Settings.DecimalPrecisionContext.Value))) + foreach (var root in roots) + { + if (root.Evaled is not Complex { IsFinite: true } value) + return null; + values.Add((root, value)); + } + var scale = EDecimal.Zero; + foreach (var (_, value) in values) + scale = EDecimal.Max(scale, EDecimal.Max(value.RealPart.EDecimal.Abs(), value.ImaginaryPart.EDecimal.Abs())); + var read = new List(); + foreach (var (root, value) in values) + { + // True where an enclosure is off the real line, false where one is on it. + bool? offTheLine = null; + var found = false; + foreach (var precision in EnclosureDigits) + if (Numerics.PreciseEvaluation.Of(root, precision) is { } enclosure) + { + found = true; + if (enclosure.Im.Low.Sign > 0 || enclosure.Im.High.Sign < 0) + offTheLine = true; + else if (enclosure.Im.IsZero) + offTheLine = false; + if (offTheLine is not null) + break; + } + if (offTheLine is true) + read.Add(null); + else if (offTheLine is false || value is Real || value.ImaginaryPart.EDecimal.IsZero) + read.Add(new(root, value.RealPart, scale)); + else if (!found && IsClearOfZero(value.ImaginaryPart.EDecimal, scale, besideOne: false)) + read.Add(null); + else + return null; + } + return read; + } + + /// + /// The sign of less , or null where it is not + /// decided: by their exact values where both are rational, by enclosures of them where those + /// are apart, as 0 where they are written alike; and where no enclosure is found, by their + /// decimals, beside the size of the roots they were found with. + /// + private static int? Compare(Point left, Point right) + { + if (left.Exact == right.Exact) + return 0; + if (left.Exact is Rational exactLeft && right.Exact is Rational exactRight) + return exactLeft.ERational.CompareTo(exactRight.ERational); + var enclosed = false; + foreach (var precision in EnclosureDigits) + { + if (left.Enclosure(precision) is not { } a || right.Enclosure(precision) is not { } b) + continue; + enclosed = true; + if (a.Re.High.CompareTo(b.Re.Low) < 0) + return -1; + if (a.Re.Low.CompareTo(b.Re.High) > 0) + return 1; + } + if ((left.Exact - right.Exact).InnerSimplified is Integer { IsZero: true }) + return 0; + if (enclosed) + return null; + var difference = left.Value.EDecimal.Subtract(right.Value.EDecimal); + return IsClearOfZero(difference, EDecimal.Max(left.Scale, right.Scale), besideOne: false) ? difference.Sign : null; + } + + /// + /// Whether is between and + /// , an end that is null being an infinity; null where that is not decided. + /// + private static bool? Within(Point root, Point? left, Point? right) + { + if (left is not null) + switch (Compare(root, left)) + { + case null: return null; + case < 0: return false; + } + if (right is not null) + switch (Compare(root, right)) + { + case null: return null; + case > 0: return false; + } + return true; + } + + /// + /// The sign of , a real number, or null where it is not decided: + /// exactly where it is rational, and otherwise by an enclosure of it, or by its decimal without + /// the exponent floor where no enclosure is found. + /// + private static int? SignOf(Entity value) + { + value = value.InnerSimplified; + if (value is Rational exact) + return exact.ERational.Sign; + Complex number; + using (MathS.Settings.DecimalPrecisionContext.Set(InternalAMExtensions.WithUnboundedExponents(MathS.Settings.DecimalPrecisionContext.Value))) + if (value.Evaled is not Complex { IsFinite: true } evaluated) + return null; + else + number = evaluated; + var point = new Point(value, number.RealPart); + return number.ImaginaryPart.EDecimal.IsZero ? Compare(point, new(Integer.Zero, Integer.Zero)) : null; + } + + /// + /// Whether is zero, or null where that is not decided: exactly where + /// it is rational, not zero where an enclosure of it is clear of zero, and zero where it + /// evaluates to 0 without the exponent floor, two decimals that agree being equal as they are + /// in a comparison. https://github.com/asc-community/AngouriMath/issues/1376 + /// + private static bool? IsZero(Entity constant) + { + if (constant is Rational exact) + return exact.ERational.IsZero; + foreach (var precision in EnclosureDigits) + if (Numerics.PreciseEvaluation.Of(constant, precision) is { } enclosure + && (!enclosure.Re.ContainsZero || !enclosure.Im.ContainsZero)) + return false; + using var _ = MathS.Settings.DecimalPrecisionContext.Set(InternalAMExtensions.WithUnboundedExponents(MathS.Settings.DecimalPrecisionContext.Value)); + return constant.Evaled is Complex { IsZero: true } ? true : null; + } /// /// The complex at which is zero, where it is @@ -388,7 +610,7 @@ private static bool TryReadReal(Entity value, out Real? real) // https://github.com/asc-community/AngouriMath/issues/2650 case Complex { IsFinite: true } complex: return IsClearOfZero(complex.ImaginaryPart.EDecimal, - PeterO.Numbers.EDecimal.Max(complex.RealPart.EDecimal.Abs(), complex.ImaginaryPart.EDecimal.Abs()), besideOne: false); + EDecimal.Max(complex.RealPart.EDecimal.Abs(), complex.ImaginaryPart.EDecimal.Abs()), besideOne: false); default: return false; } @@ -398,8 +620,8 @@ private static bool TryReadReal(Entity value, out Real? real) /// Whether is too large, beside , to be /// what rounding leaves of a zero. /// - private static bool IsClearOfZero(PeterO.Numbers.EDecimal part, PeterO.Numbers.EDecimal scale, bool besideOne = true) - => part.Abs().CompareTo(PeterO.Numbers.EDecimal.FromString("1E-30").Multiply(besideOne ? PeterO.Numbers.EDecimal.Max(PeterO.Numbers.EDecimal.One, scale.Abs()) : scale.Abs())) > 0; + private static bool IsClearOfZero(EDecimal part, EDecimal scale, bool besideOne = true) + => part.Abs().CompareTo(EDecimal.FromString("1E-30").Multiply(besideOne ? EDecimal.Max(EDecimal.One, scale.Abs()) : scale.Abs())) > 0; /// /// An expression as (Real + Imaginary i) / Denominator, each of the three real diff --git a/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs b/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs index 6275ec659..d3856c47f 100644 --- a/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/SolverRegressionTest.cs @@ -593,5 +593,90 @@ public void Issue2450_EquationsReadsAConjunctionAsItsEquations(string[] written, [InlineData("x + y = 3 and x - y = 1 and x in RR")] public void Issue2450_EquationsKeepsAConjunctionWithAnotherConjunct(string written) => Assert.Null(MathS.Equations(written).Solve("x", "y")); + + // Over the reals a root of a piece between two kinks of the moduli was kept only where it evaluated to a real + // inside the piece, and otherwise left out as though it were known not to be one. With x written 10^30 x the + // decimals flushed the parts of the quartic's roots, near 10^-31, and read them as complex numbers near 2.27, + // so all eight were left out and the equation was answered { }. Its four real roots are those of + // x^4 - 10 x^2 + |x| + 1 = 0 over 10^30. Declining is an answer too; { } is not. + // https://github.com/asc-community/AngouriMath/issues/2659 + [Fact] + public void Issue2659_ARootThatIsNotReadAsARealIsNotLeftOut() + { + using var _ = MathS.Settings.Codomain.Set(AngouriMath.Core.Domain.Real); + var solved = "(10^30 x)^4 - 10 (10^30 x)^2 + abs(10^30 x) + 1 = 0".ToEntity().Solve("x"); + if (solved is not Entity.Set.FiniteSet roots) + return; + var expected = UnflooredValues("x^4 - 10 x^2 + abs(x) + 1 = 0".ToEntity().Solve("x")); + Assert.Equal(4, expected.Count); + var values = UnflooredValues(roots); + Assert.Equal(expected.Count, values.Count); + foreach (var value in expected) + Assert.Contains(values, root => IsCloseRelative(root.ScaleByPowerOfTen(30), value)); + } + + // A root of a piece that is not decided to be real, or not decided to be in the piece, declines the equation, + // whatever made it undecided. x^4 - 10 x^2 - |x| + 10^-150 = 0 has four real roots, two near 3.21 and two near + // 10^-150; the quartic formula's roots of a piece were 0 in place of the one near -10^-150, which the piece's + // equation is 10^-150 at, and a root near 10^-150 that terms near 3 cancel to is rounding at a hundred digits. + // Leaving either out answered the equation without them. + // https://github.com/asc-community/AngouriMath/issues/2659 + [Theory] + [InlineData("x^4 - 10 x^2 - abs(x) + 10^(-150)")] + [InlineData("x^4 - 10 x^2 - abs(x) + 10^(-70)")] + public void Issue2659_AnUndecidedRootOfAPieceDeclines(string expression) + { + using var _ = MathS.Settings.Codomain.Set(AngouriMath.Core.Domain.Real); + var solved = AngouriMath.Functions.Algebra.AnalyticalSolving.ModulusSolver.SolveOverTheReals(expression.ToEntity(), MathS.Var("x")); + if (solved is null) + return; + var values = UnflooredValues(solved); + Assert.Equal(4, values.Count); + Assert.Equal(2, values.Count(value => value.Abs().CompareTo(PeterO.Numbers.EDecimal.FromString("1E-60")) < 0 && !value.IsZero)); + } + + // What is decided still answers: a root a hair past the kink at 1, told from it by an enclosure, is left out, + // and the roots of pieces with none real leave { }. + // https://github.com/asc-community/AngouriMath/issues/2659 + [Theory] + [InlineData("abs(x - 1) + x^2 - 1 - 10^(-40)", 2)] + [InlineData("x^4 - 10 x^2 + abs(x) + 1", 4)] + [InlineData("x^4 - 10 x^2 - abs(x) + 10^(-30)", 4)] + [InlineData("x^4 + 10 x^2 + abs(x) + 1", 0)] + [InlineData("(10^30 x)^4 + 10 (10^30 x)^2 + abs(10^30 x) + 1", 0)] + [InlineData("x^2 + abs(x) + 1", 0)] + [InlineData("abs(x) + x^2 - 2", 2)] + public void Issue2659_ADecidedRootIsStillAnswered(string expression, int count) + { + using var _ = MathS.Settings.Codomain.Set(AngouriMath.Core.Domain.Real); + var solved = AngouriMath.Functions.Algebra.AnalyticalSolving.ModulusSolver.SolveOverTheReals(expression.ToEntity(), MathS.Var("x")); + Assert.NotNull(solved); + var x = MathS.Var("x"); + var values = UnflooredValues(solved!); + Assert.Equal(count, values.Count); + using var unfloored = MathS.Settings.DecimalPrecisionContext.Set(Unfloored); + foreach (var root in (Entity.Set.FiniteSet)solved!) + { + var residual = (Entity.Number.Complex)expression.ToEntity().Substitute(x, root).Evaled; + Assert.True(residual.Abs().EDecimal.Abs().CompareTo(PeterO.Numbers.EDecimal.FromString("1E-50")) < 0, residual.Stringize()); + } + } + + private static readonly PeterO.Numbers.EContext Unfloored = new(100, PeterO.Numbers.ERounding.HalfUp, -100000, 100000, false); + + // Real parts, evaluated without the exponent floor, of roots each checked to be real. + private static System.Collections.Generic.List UnflooredValues(Entity.Set solved) + { + using var _ = MathS.Settings.DecimalPrecisionContext.Set(Unfloored); + return Assert.IsType(solved).Select(root => + { + var value = Assert.IsAssignableFrom(root.Evaled); + Assert.True(value.ImaginaryPart.EDecimal.Abs().CompareTo(value.RealPart.EDecimal.Abs().Multiply(PeterO.Numbers.EDecimal.FromString("1E-40"))) <= 0, value.Stringize()); + return value.RealPart.EDecimal; + }).ToList(); + } + + private static bool IsCloseRelative(PeterO.Numbers.EDecimal a, PeterO.Numbers.EDecimal b) + => a.Subtract(b).Abs().CompareTo(b.Abs().Multiply(PeterO.Numbers.EDecimal.FromString("1E-40"))) <= 0; } }