diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 9d3e6e7b8..3ddc7bcf3 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -503,6 +503,32 @@ before v3, which decides exact comparisons exactly (#1019 §10). Two decimals th | `sqrt(5)^1000 = 5^500` | `False` | stays written | | `sqrt(2) < sqrt(2) + 10^(-150)` | `False` | stays written | +### A finite set holds a member written another way + +**Silent: wrong answers become right ones.** A finite set looked its members up by their hundred-digit evaluations, +and one number written two ways can evaluate to decimals that differ in the last digit: `sqrt(8)` ends `...283145` and +`2 sqrt(2)` ends `...283146`. A miss on the decimal was taken for "not a member", so a set rejected its own element, +kept it twice, and did not take it out. Members whose evaluations agree that far are now compared as numbers: the same +where their difference simplifies to 0, different where enclosures in twice the working digits are apart, and otherwise +undecided. An evaluated set has only the decimals, which decide nothing at that distance, so an operation on two such +sets stays written where it gave a wrong set. Measured on master `578680eed` and on this branch +([#2755](https://github.com/asc-community/AngouriMath/issues/2755)). + +| | Was (`578680eed`) | Now | +|---|---|---| +| `TryContains`: `sqrt(8)` in `{ 2 sqrt(2) }` | decided, not a member | decided, a member | +| `TryContains`: `sqrt(8)` in `{ x, 2 sqrt(2) }` | undecided | decided, a member | +| `(sqrt(8) in { -2 sqrt(2), 2 sqrt(2) }).Simplify()` | `False` | `True` | +| `(cos(pi/5) in { (1 + sqrt(5))/4 }).Evaled` | `False` | `True` | +| `{ (1 + sqrt(2))^2, 3 + 2 sqrt(2) }.Simplify()` | `{ (1 + sqrt(2)) ^ 2, 3 + 2 * sqrt(2) }` | `{ 3 + 2 * sqrt(2) }` | +| `({ (1 + sqrt(2))^2 } \ { 3 + 2 sqrt(2) }).Simplify()` | `{ (1 + sqrt(2)) ^ 2 }` | `{ }` | +| `({ (1 + sqrt(2))^2 } /\ { 3 + 2 sqrt(2) }).Simplify()` | `{ }` | `{ (1 + sqrt(2)) ^ 2 }` | +| `({ sin(pi/3) } = { sqrt(3)/2 }).Simplify()` | `False` | `True` | +| `({ sqrt(8) } \ { 2 sqrt(2) }).Evaled` | `{ 2.8284...283145 }` | the difference of the two evaluated sets, unevaluated | + +Two numbers whose evaluations agree in every digit still share a key, and `pi + 10^(-120) in { pi }` is still +`True`: that is [#1376](https://github.com/asc-community/AngouriMath/issues/1376). + ### A square system is answered exactly whichever order its equations are in **Not silent: a decimal answer is now exact, and a refused system has an answer.** The eliminator took the last diff --git a/Sources/.editorconfig b/Sources/.editorconfig index fdd52020c..da69a0c8b 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -733,6 +733,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [AngouriMath/Core/Entity/Omni/Sets/Cardinality.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n +[AngouriMath/Core/Entity/Omni/Sets/FiniteSet.SameNumber.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + [Tests/UnitTests/Core/Sets/SubsetTest.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n diff --git a/Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs b/Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs index a7b847f9b..c8cfaa861 100644 --- a/Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs +++ b/Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs @@ -81,7 +81,7 @@ private static Dictionary BuildDictionaryFromElements(IEnumerabl else dict[elem.Evaled] = dict.TryGetValue(elem.Evaled, out var value) ? Simplificator.PickSimplest(elem, value) : elem; } - return dict; + return noCheck ? dict : WithRespelledMembersMerged(dict); } /// @@ -130,7 +130,25 @@ internal static bool TryFullSubtract(FiniteSet A, FiniteSet B, [NotNullWhen(true var constantSets = A.Vars.Count == 0 && B.Vars.Count == 0; var dict = BuildDictionaryFromElements(A.Elements, noCheck: true); foreach (var el in B) - if (!dict.Remove(el.Evaled) && !constantSets) { resultSet = null; return false; } + { + if (dict.Remove(el.Evaled)) + continue; + if (!constantSets) { resultSet = null; return false; } + // A member of B written otherwise than in A is taken out of A where it is + // the same number, and leaves the difference as written where that is + // not decided. https://github.com/asc-community/AngouriMath/issues/2755 + if (el.Evaled is not Complex value) + continue; + switch (MemberWithTheValueOf(dict, el, value, out var key)) + { + case true: + dict.Remove(key!); + break; + case null: + resultSet = null; + return false; + } + } resultSet = new FiniteSet(dict.Values, noCheck: true); // we didn't add anything return true; } @@ -142,6 +160,28 @@ public override bool TryContains(Entity entity, out bool contains) contains = elements.ContainsKey(entity.Evaled); // x in { x, 2 } and 2 in { x, 2 } are both unambiguously true if (contains) return true; + // The keys are evaluations rounded to the working digits, and sqrt(8) in + // { 2 sqrt(2) } misses its key in the last digit, so the members near it are + // compared as numbers, and a set as an element with the sets among the members. + // One shown the same makes it a member whatever the others are: + // sqrt(8) in { x, 2 sqrt(2) }. One not shown either way leaves it undecided. + // https://github.com/asc-community/AngouriMath/issues/2755 + if (entity.Vars.Count == 0) + { + var byValue = entity.Evaled switch + { + FiniteSet listed => MemberWithTheMembersOf(elements, entity as FiniteSet ?? listed), + Complex value => MemberWithTheValueOf(elements, entity, value, out _), + _ => false, + }; + if (byValue is true) + { + contains = true; + return true; + } + if (byValue is null) + return false; + } // however, 1 in { x, 2 }, y in { x, 2 } are both unknown // meanwhile, 2 in { 1, 3 } is unambiguously false return entity.Vars.Count == 0 && elements.Keys.All(el => el.Vars.Count == 0); @@ -164,8 +204,10 @@ public bool Equals(FiniteSet? other) return false; if (other.Count != Count) return false; + // Equality of entities compares the members' evaluations and proves nothing: + // it is not the membership, which can simplify to decide. foreach (var pair in elements) - if (!other.TryContains(pair.Key, out var contains) || !contains) + if (!other.elements.ContainsKey(pair.Key)) return false; return true; } diff --git a/Sources/AngouriMath/Core/Entity/Omni/Sets/FiniteSet.SameNumber.cs b/Sources/AngouriMath/Core/Entity/Omni/Sets/FiniteSet.SameNumber.cs new file mode 100644 index 000000000..4be001bf7 --- /dev/null +++ b/Sources/AngouriMath/Core/Entity/Omni/Sets/FiniteSet.SameNumber.cs @@ -0,0 +1,260 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using AngouriMath.Numerics; +using PeterO.Numbers; + +namespace AngouriMath +{ + partial record Entity + { + partial record Set + { + partial record FiniteSet + { + /// + /// Whether two members without variables whose evaluations differ are the same number: + /// where their difference simplifies to 0, + /// where their values are apart, and + /// where neither is shown. + /// + /// + /// + /// A finite set keys its members by their evaluations, which are rounded to the + /// working digits, so one number written two ways can be two keys: + /// sqrt(8) evaluates to ...283145 and 2 sqrt(2) to + /// ...283146. A miss on the key was taken for "not a member", and + /// sqrt(8) in { 2 sqrt(2) } was false. + /// https://github.com/asc-community/AngouriMath/issues/2755 + /// + /// + /// Values that differ by more than , + /// relative to the larger of them and 1, are different numbers, as a miss on the key + /// has always said. Nearer than that the evaluations cannot tell, and the two are + /// compared by enclosures in twice the working digits, which are apart only where + /// the numbers are, and then by simplifying their difference, which is 0 only where + /// they are equal. A difference that simplifies to a nonzero rational settles them + /// apart. Anything else is not decided, and so is a pair of which one is a decimal: + /// an evaluated set has its members rounded, and 2.8284...145 and + /// 2.8284...146 are where sqrt(8) and 2 sqrt(2) were. + /// + /// + internal static bool? SameNumber(Entity left, Complex leftValue, Entity right, Complex rightValue) + { + if (!AreNear(leftValue, rightValue)) + return false; + // A decimal is what an evaluation rounded, and two that agree this far are + // not told apart by it, as an equality of two such decimals is not decided. + if (left is Number { IsExact: false } || right is Number { IsExact: false }) + return null; + var digits = EnclosureDigits; + if (PreciseEvaluation.Of(left, digits) is { } leftBox + && PreciseEvaluation.Of(right, digits) is { } rightBox + && (Apart(leftBox.Re, rightBox.Re) || Apart(leftBox.Im, rightBox.Im))) + return false; + var difference = (left - right).Simplify(); + if (difference is Integer { IsZero: true }) + return true; + if (difference is Complex { RealPart: Rational, ImaginaryPart: Rational }) + return false; + return null; + } + + /// + /// Whether two finite evaluations are within + /// of each other in both parts, relative to the larger of their parts and 1. Values + /// that are not finite are near nothing: two equal infinities share a key. + /// + private static bool AreNear(Complex left, Complex right) + { + if (!left.IsFinite || !right.IsFinite) + return false; + var context = Thirty; + var gap = EDecimal.Max( + left.RealPart.EDecimal.Subtract(right.RealPart.EDecimal, context).Abs(), + left.ImaginaryPart.EDecimal.Subtract(right.ImaginaryPart.EDecimal, context).Abs()); + return gap.CompareTo(MathS.Settings.DowncastingTolerance.Multiply(Scale(left, right), context)) <= 0; + } + + [AngouriMath.Core.ConstantField] + private static readonly EContext Thirty = EContext.ForPrecision(30); + + private static EDecimal Scale(Complex left, Complex right) + => EDecimal.Max(EDecimal.One, EDecimal.Max( + EDecimal.Max(left.RealPart.EDecimal.Abs(), left.ImaginaryPart.EDecimal.Abs()), + EDecimal.Max(right.RealPart.EDecimal.Abs(), right.ImaginaryPart.EDecimal.Abs()))); + + private static bool Apart(PreciseInterval left, PreciseInterval right) + => left.High.CompareTo(right.Low) < 0 || right.High.CompareTo(left.Low) < 0; + + // Twice the working digits: two numbers the evaluations put within their last digit + // of each other, as pi and pi + 10^(-100) are, are told apart where they differ. + private static int EnclosureDigits + { + get + { + var precision = MathS.Settings.DecimalPrecisionContext.Value.Precision; + return precision.CanFitInInt32() ? System.Math.Min(System.Math.Max(2 * precision.ToInt32Unchecked(), 50), 2000) : 2000; + } + } + + /// + /// , which has no variables, against the members of the + /// set near it, where its key is not one of theirs: where + /// one of them is the same number, where each is apart from + /// it, and where one is neither shown the same nor apart. + /// The key of the member found is in . + /// + private static bool? MemberWithTheValueOf(Dictionary members, Entity entity, Complex value, out Entity? key) + { + key = null; + var undecided = false; + foreach (var pair in members) + { + if (pair.Key is not Complex memberValue || IsExact(value) && IsExact(memberValue) || !AreNear(value, memberValue)) + continue; + switch (SameNumber(entity, value, pair.Value, memberValue)) + { + case true: + key = pair.Key; + return true; + case null: + undecided = true; + break; + } + } + return undecided ? null : false; + } + + /// + /// A finite set without variables against the members of the set that are finite + /// sets, as written, by each holding the other's: { sqrt(8) } is the + /// member { 2 sqrt(2) }. where one is the same set, + /// where each is shown another, + /// where one is neither. + /// + private static bool? MemberWithTheMembersOf(Dictionary members, FiniteSet set) + { + var undecided = false; + foreach (var pair in members) + { + if (pair.Key is not FiniteSet || pair.Value is not FiniteSet member || member.Vars.Count != 0) + continue; + if (!set.TryIsSubsetOf(member, out var inside) || inside && !member.TryIsSubsetOf(set, out inside)) + undecided = true; + else if (inside) + return true; + } + return undecided ? null : false; + } + + /// + /// with the members that are the same number written + /// two ways made one, the simplest of the spellings at the place of the first. + /// Members whose evaluations are near but not shown the same are both kept, as a + /// set whose members are not known to differ is written. + /// https://github.com/asc-community/AngouriMath/issues/2755 + /// + /// + /// Two exact keys that differ are different numbers, so a set whose members all + /// evaluate to rationals is returned as it is, and so is one whose members are + /// apart in doubles: this runs on every set that is built. + /// + private static Dictionary WithRespelledMembersMerged(Dictionary members) + { + if (members.Count < 2) + return members; + var anyInexact = false; + foreach (var key in members.Keys) + if (key is Complex { IsFinite: true } candidate && !IsExact(candidate)) + { + anyInexact = true; + break; + } + if (!anyInexact) + return members; + List<(int Index, Complex Value, double Re, double Im)>? numbers = null; + var anInexactKey = false; + var index = 0; + foreach (var pair in members) + { + if (pair.Key is Complex { IsFinite: true } value && pair.Value.Vars.Count == 0) + { + (numbers ??= new()).Add((index, value, Roughly(value.RealPart.EDecimal), value is Real ? 0 : Roughly(value.ImaginaryPart.EDecimal))); + anInexactKey |= !IsExact(value); + } + index++; + } + if (numbers is null || numbers.Count < 2 || !anInexactKey) + return members; + // Doubles carry sixteen digits, and two values near in the working digits are + // within the doubles' own rounding of each other, which the window allows many + // times over; it is only a sieve for the comparison of the decimals. + var largest = 1.0; + foreach (var number in numbers) + largest = System.Math.Max(largest, System.Math.Max(System.Math.Abs(number.Re), System.Math.Abs(number.Im))); + var window = System.Math.Max(MathS.Settings.DowncastingToleranceAsDouble, 1e-12) * largest; + numbers.Sort(static (a, b) => a.Re.CompareTo(b.Re)); + var entries = members.ToArray(); + int[]? mergedInto = null; + for (var i = 0; i < numbers.Count; i++) + for (var j = i + 1; j < numbers.Count && !(numbers[j].Re - numbers[i].Re > window); j++) + { + if (System.Math.Abs(numbers[j].Im - numbers[i].Im) > window + || IsExact(numbers[i].Value) && IsExact(numbers[j].Value)) + continue; + var (first, second) = numbers[i].Index < numbers[j].Index ? (numbers[i], numbers[j]) : (numbers[j], numbers[i]); + if (mergedInto is not null && (mergedInto[first.Index] != first.Index || mergedInto[second.Index] != second.Index)) + continue; + if (SameNumber(entries[first.Index].Value, first.Value, entries[second.Index].Value, second.Value) is not true) + continue; + if (mergedInto is null) + { + mergedInto = new int[entries.Length]; + for (var k = 0; k < mergedInto.Length; k++) + mergedInto[k] = k; + } + mergedInto[second.Index] = first.Index; + entries[first.Index] = new(entries[first.Index].Key, Simplificator.PickSimplest(entries[first.Index].Value, entries[second.Index].Value)); + } + if (mergedInto is null) + return members; + var merged = new Dictionary(members.Count); + for (var k = 0; k < entries.Length; k++) + if (mergedInto[k] == k) + merged[entries[k].Value.Evaled] = entries[k].Value; + return merged; + } + + /// + /// as a double to about fifteen digits, from the leading bits of + /// its mantissa: the conversion that rounds correctly costs microseconds on a hundred digits, + /// and a set is built far more often than it has two members near each other. Beyond the + /// doubles' range it is an infinity or 0, which every member near it shares. + /// + private static double Roughly(EDecimal value) + { + if (value.IsZero) + return 0; + var mantissa = value.Mantissa; + var bits = mantissa.Abs().GetUnsignedBitLengthAsInt64(); + var shift = (int)System.Math.Max(0, bits - 62); + var leading = (double)mantissa.ShiftRight(shift).ToInt64Unchecked(); + if (!value.Exponent.CanFitInInt32()) + return value.Exponent.Sign > 0 ? leading * double.PositiveInfinity : 0; + // 2^shift written into the exponent bits, exact for every shift a double can hold; + // past that the value is beyond the doubles' range. + var twoToTheShift = shift <= 1023 ? System.BitConverter.Int64BitsToDouble((long)(shift + 1023) << 52) : double.PositiveInfinity; + return leading * twoToTheShift * System.Math.Pow(10, value.Exponent.ToInt32Unchecked()); + } + + /// A key that is a rational, or has rational parts: it is the number exactly. + private static bool IsExact(Complex value) => value.RealPart is Rational && value.ImaginaryPart is Rational; + } + } + } +} diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs index 07ea2739a..c5892e7c5 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs @@ -615,6 +615,10 @@ protected override Entity InnerSimplify(bool isExact) => ExpandOnTwoArguments(Element, SupSet, (a, b) => (a, b) switch { + // Evaluated, a member written otherwise than the element is a decimal + // apart from the element's in the last digits, and is not decided by it: + // the written set is asked instead. + (Number or FiniteSet, FiniteSet set) when !isExact && !set.TryContains(a, out _) && ContainsAsWritten() is { } written => written, (var el, Set set) when set.TryContains(el, out var contains) => contains, // A whole number, by what the quantifiers around it establish, is in // ZZ* where it is not negative. https://github.com/asc-community/AngouriMath/issues/1409 @@ -623,6 +627,20 @@ protected override Entity InnerSimplify(bool isExact) _ => null }, (@this, a, b) => ((Inf)@this).New(a, b), isExact, propagateSet: false); + + /// + /// Whether a constant element is in a finite set, decided on what they + /// are written as rather than on their evaluations, which round each member on its + /// own: sqrt(8) in { 2 sqrt(2) } evaluated to False. + /// https://github.com/asc-community/AngouriMath/issues/2755 + /// + private Entity? ContainsAsWritten() + { + if (Element.Vars.Count != 0) + return null; + return (SupSet as FiniteSet ?? SupSet.InnerSimplified as FiniteSet) is { } written + && written.TryContains(Element, out var contains) ? contains : null; + } } partial record Subsetf diff --git a/Sources/Tests/UnitTests/Core/Sets/Contains.cs b/Sources/Tests/UnitTests/Core/Sets/Contains.cs index 74ebe0603..3d2b13ac9 100644 --- a/Sources/Tests/UnitTests/Core/Sets/Contains.cs +++ b/Sources/Tests/UnitTests/Core/Sets/Contains.cs @@ -36,6 +36,7 @@ public sealed class Contains [InlineData("{ a, b, { 1, b } }", "2b", false, false)] [InlineData("{ 1, 2 }", "x^3", false, false)] [InlineData("{ 1, 2, { x } }", "x^3", false, false)] + [InlineData("{ x, 2 sqrt(2) }", "sqrt(2)", false, false)] [InlineData("[0; 3)", "2", true)] [InlineData("[3; -3]", "0", false)] [InlineData("[2; 2]", "2", true)] @@ -117,6 +118,55 @@ public void Test(string given, string expected, bool containsExpected, bool tryC Assert.Equal(containsExpected, containsActual); } + // A finite set keys its members by their hundred-digit evaluations, and one number written + // two ways can differ in the last digit: a miss on the key was "not a member". + // https://github.com/asc-community/AngouriMath/issues/2755 + [Theory] + [InlineData("sqrt(8)", "{ 2 sqrt(2) }", true)] + [InlineData("1/sqrt(2)", "{ sqrt(2) / 2 }", true)] + [InlineData("sin(pi/4)", "{ sqrt(2) / 2 }", true)] + [InlineData("sin(pi/3)", "{ sqrt(3) / 2 }", true)] + [InlineData("sqrt(3)/3", "{ 1/sqrt(3) }", true)] + [InlineData("(1 + sqrt(2))^2", "{ 3 + 2 sqrt(2) }", true)] + [InlineData("1/2 + sqrt(5)/2", "{ (1 + sqrt(5)) / 2 }", true)] + [InlineData("sqrt(8)", "{ -2 sqrt(2), 2 sqrt(2) }", true)] + [InlineData("sqrt(-8)", "{ 2 sqrt(2) * i }", true)] + [InlineData("sqrt(8) - 2 sqrt(2)", "{ 0 }", true)] + [InlineData("sqrt(8)", "{ x, 2 sqrt(2) }", true)] + [InlineData("{ sqrt(8) }", "{ { 2 sqrt(2) }, 1 }", true)] + [InlineData("{ sqrt(8), 1 }", "{ { 2 sqrt(2) }, { 1 } }", false)] + // Near in the evaluations and different numbers: told apart, not left undecided. + [InlineData("pi + 10^(-60)", "{ pi }", false)] + [InlineData("pi * 10^(-80)", "{ e * 10^(-80) }", false)] + [InlineData("-2 sqrt(2)", "{ 2 sqrt(2) }", false)] + public void ARespelledMemberIsAMember(string element, string set, bool expected) + { + var finite = Assert.IsType(set.ToEntity()); + Assert.True(finite.TryContains(element.ToEntity(), out var contains)); + Assert.Equal(expected, contains); + Assert.Equal(expected ? Boolean.True : Boolean.False, $"{element} in {set}".ToEntity().Evaled); + Assert.Equal(expected ? Boolean.True : Boolean.False, $"{element} in {set}".ToEntity().Simplify()); + } + + [Theory] + [InlineData("{ sqrt(8), 2 sqrt(2) }", 1)] + [InlineData("{ (1 + sqrt(2))^2, 3 + 2 sqrt(2), 1 }", 2)] + [InlineData("{ 1/sqrt(2) } \\/ { sqrt(2) / 2 }", 1)] + [InlineData("{ (1 + sqrt(2))^2 } \\ { 3 + 2 sqrt(2) }", 0)] + [InlineData("{ (1 + sqrt(2))^2, 1 } \\ { 3 + 2 sqrt(2) }", 1)] + [InlineData("{ (1 + sqrt(2))^2 } /\\ { 3 + 2 sqrt(2) }", 1)] + [InlineData("{ pi, pi + 10^(-60) }", 2)] + public void ARespelledMemberIsOneMember(string set, int count) + => Assert.Equal(count, Assert.IsType(set.ToEntity().Simplify()).Count); + + // Evaluated, the members are decimals that differ in the last digits, which decide + // nothing: the operation stays written rather than keeping a member it took out. + [Theory] + [InlineData("{ sqrt(8) } \\ { 2 sqrt(2) }")] + [InlineData("{ (1 + sqrt(2))^2 } /\\ { 3 + 2 sqrt(2) }")] + public void AnEvaluatedRespellingIsNotDecided(string operation) + => Assert.IsNotType(operation.ToEntity().Evaled); + [Theory] [InlineData("{ x : x = a and x > a }", "a", false)] public void TestSkip(string given, string expected, bool containsExpected)