diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index edd19a65c..9d15440d7 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -745,15 +745,20 @@ of [#1409](https://github.com/asc-community/AngouriMath/issues/1409) — is `Tru ### `image` and `preimage` of a set under an expression `image(f(x), x in A)` is `{ f(x) : x in A }` — `union({f(x)}, x in A)` — listed over a listed -`A`, an interval by interval arithmetic where `x` occurs once in `f`, and a membership object -otherwise; `preimage(f(x), x in A, Y)` is `{ x in A : f(x) in Y }`, and a set builder of that -shape is solved on evaluation where the membership is read (a listed `Y`, an interval) +`A`, an interval by interval arithmetic where `x` occurs once in `f`, intervals read off the +critical points and the one-sided limits where `f` is a quotient of polynomials with rational +coefficients and `A` is made of intervals (§7.3.5 Try 1's `x/(1 + x)` on `RR \ {-1}` is +`RR \ {1}`), and a membership object otherwise; `preimage(f(x), x in A, Y)` is +`{ x in A : f(x) in Y }`, and a set builder of that shape is solved on evaluation where the +membership is read (a listed `Y`, an interval) ([#1409](https://github.com/asc-community/AngouriMath/issues/1409), Sullivan and Mackey's §7.3). Both names are keywords now, and were names. | Input | Was (2.5.0) | Now | |---|---|---| | `image(9 c / 5 + 32, c in (0; 100))` | `UnhandledParseException` | `(32; 212)` | +| `image(x^2/(1 + x^2), x in RR)` | `UnhandledParseException` | `[0; 1)` | +| `image(x/(1 + x), x in RR \ {-1})` | `UnhandledParseException` | `(-oo; 1) \/ (1; +oo)` | | `preimage(x^2, x in RR, {1})` | `UnhandledParseException` | `{ 1, -1 }` | | `{ x in ZZ : x^2 in {1, 4} }` | `{ x in ZZ : x ^ 2 in { 1, 4 } }` — left as written | `{ 1, -1, 2, -2 }` | diff --git a/Sources/.editorconfig b/Sources/.editorconfig index 80e2bd225..14775f65f 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -288,6 +288,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [Tests/UnitTests/Core/Sets/IntervalImageTest.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/Functions/Continuous/ImageByCalculus.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/Functions/Boolean/Quantifiers.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/Functions/Continuous/ImageByCalculus.cs b/Sources/AngouriMath/Functions/Continuous/ImageByCalculus.cs new file mode 100644 index 000000000..8917e9baf --- /dev/null +++ b/Sources/AngouriMath/Functions/Continuous/ImageByCalculus.cs @@ -0,0 +1,253 @@ +// +// 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 System.Collections.Generic; +using System.Linq; +using PeterO.Numbers; +using static AngouriMath.Entity; +using static AngouriMath.Entity.Number; +using static AngouriMath.Entity.Set; + +namespace AngouriMath.Functions +{ + /// + /// The image of a set of reals under a quotient of polynomials, { f(x) : x in S }, read + /// off the function's critical points and its limits: Sullivan and Mackey's §7.3.5 Try 1, + /// x/(1 + x) over RR \ {-1}, is RR \ {1}, and Prob 7.8.8's + /// (2x - 1)/(2x (1 - x)) over (0, 1) is RR. + /// + /// + /// + /// A continuous function maps an interval onto an interval, and a differentiable one is + /// monotone between the zeros of its derivative, so the image of an interval without a pole is + /// the interval between the least and the greatest of the values at the critical points inside + /// it, the values at its closed ends and the one-sided limits at its open ones. An end of the + /// image is closed where the value is taken, at a critical point or a closed end, and open + /// where it is only approached. The set is cut into such intervals first: at the points a + /// difference removes, and at the poles, where the function is not defined. + /// + /// + /// The derivative's zeros have to be all of them, or a turning point is missed and the image + /// comes out too small. So the numerator of the derivative, and the denominator whose zeros + /// are the poles, have to be polynomials of degree four or less, which the solver answers in + /// radicals completely; the coefficients have to be rational, so that a coefficient which + /// cancels is zero rather than a residue; and every root has to evaluate, a real one to a + /// candidate and a non-real one to nothing. A real root can come out of the radicals with an + /// imaginary residue near 1e-99, which is read as zero below the downcasting tolerance + /// whether downcasting is on or not. + /// + /// https://github.com/asc-community/AngouriMath/issues/1409 + /// + internal static class ImageByCalculus + { + /// The highest degree whose roots the solver lists completely, in radicals. + private const int MaxDegree = 4; + + /// The largest whole exponent read, so that nothing large is expanded to find a degree. + private const int MaxExponent = 8; + + internal static Set? Of(Entity f, Variable x, Entity over) + { + if (!f.ContainsNode(x) || !IsRational(f, x) || Pieces(over) is not { } pieces) + return null; + var (numerator, denominator) = SingleQuotient.Of(f); + // The quotient rule's numerator: its zeros are the critical points. + var slope = numerator.Differentiate(x) * denominator - numerator * denominator.Differentiate(x); + if (Polynomial(denominator, x) is not { } bottom || Polynomial(slope, x) is not { } top + || RealRoots(bottom, x) is not { } poles || RealRoots(top, x) is not { } critical) + return null; + // Each piece's image once, from the left, so that the union reads in order and two + // pieces with one image are written once. + var parts = new List<(Set Part, Real From)>(); + foreach (var piece in pieces.SelectMany(piece => CutAt(piece, poles))) + { + if (Of(f, x, piece, critical) is not { } part) + return null; + if (Lowest(part) is { } from && parts.All(other => other.Part != part)) + parts.Add((part, from)); + } + Set image = Empty; + foreach (var (part, _) in parts.OrderBy(part => part.From)) + image = image.Unite(part).InnerSimplified is Set united ? united : (Set)image.Unite(part); + return image; + } + + /// Where an image of one piece starts, or for an empty one. + private static Real? Lowest(Set part) + => part switch + { + Interval interval => AsReal(interval.Left), + FiniteSet { Count: > 0 } listed => AsReal(listed.First()), + _ => null, + }; + + /// The image of one interval with no pole inside. + private static Set? Of(Entity f, Variable x, Interval piece, List<(Entity Root, Real Value)> critical) + { + if (AsReal(piece.Left) is not { } left || AsReal(piece.Right) is not { } right) + return null; + if (left.CompareTo(right) > 0 || left == right && !(piece.LeftClosed && piece.RightClosed)) + return Empty; + // Each candidate is a value, what it evaluates to, and whether it is taken. + var candidates = new List<(Entity Value, Real Number, bool Taken)>(); + foreach (var (root, at) in critical) + if (at.CompareTo(left) > 0 && at.CompareTo(right) < 0) + { + var value = f.Substitute(x, root); + if (AsReal(value) is not { IsFinite: true } number) + return null; + candidates.Add((value, number, true)); + } + if (End(f, x, piece.Left, left, piece.LeftClosed, Core.ApproachFrom.Right) is not { } atLeft + || End(f, x, piece.Right, right, piece.RightClosed, Core.ApproachFrom.Left) is not { } atRight) + return null; + candidates.Add(atLeft); + candidates.Add(atRight); + var least = candidates.Min(candidate => candidate.Number)!; + var greatest = candidates.Max(candidate => candidate.Number)!; + // Only the two that bound the image are simplified. + var lower = candidates.First(candidate => Same(candidate.Number, least)).Value.Simplify(); + var upper = candidates.First(candidate => Same(candidate.Number, greatest)).Value.Simplify(); + var lowerTaken = least.IsFinite && candidates.Any(candidate => Same(candidate.Number, least) && candidate.Taken); + var upperTaken = greatest.IsFinite && candidates.Any(candidate => Same(candidate.Number, greatest) && candidate.Taken); + // A function constant on the interval takes its one value at every point of it. + if (Same(least, greatest)) + return new FiniteSet(lower); + return new Interval(lower, lowerTaken, upper, upperTaken); + } + + /// The value at a closed end, taken, or the one-sided limit at an open one, approached. + private static (Entity Value, Real Number, bool Taken)? End(Entity f, Variable x, Entity end, Real at, bool closed, Core.ApproachFrom side) + { + if (closed && at.IsFinite) + { + var value = f.Substitute(x, end); + return AsReal(value) is { IsFinite: true } number ? (value, number, true) : null; + } + // A limit that is not found stays a limit node, which does not evaluate to a number. + var limit = at.IsFinite ? f.Limit(x, end, side) : f.Limit(x, end); + return AsReal(limit) is { IsNaN: false } approached ? (limit, approached, false) : null; + } + + /// + /// The expression as a polynomial of degree at most , its monomials + /// gathered and those that cancel dropped, or . + /// + private static Entity? Polynomial(Entity expr, Variable x) + { + if (!TreeAnalyzer.TryGetPolynomial(expr, x, out var monomials)) + return null; + Entity sum = Integer.Zero; + foreach (var monomial in monomials) + { + var power = monomial.Key; + if (monomial.Value.Evaled is not Rational exact) + return null; + if (exact.IsZero) + continue; + if (power.Sign < 0 || power.CompareTo(EInteger.FromInt32(MaxDegree)) > 0) + return null; + // The constant term as itself: x^0 is 1 only where x is not 0. + sum += power.IsZero ? exact : exact * MathS.Pow(x, Integer.Create(power)); + } + return sum.InnerSimplified; + } + + /// + /// The real roots of a polynomial with each one's value, or where the + /// solver does not list them all as numbers. + /// + private static List<(Entity Root, Real Value)>? RealRoots(Entity polynomial, Variable x) + { + if (!polynomial.ContainsNode(x)) + return new List<(Entity, Real)>(); + // The equation solver answers a polynomial it cannot list with a set that is not + // listed, rather than throwing. + if (polynomial.SolveEquation(x) is not FiniteSet listed) + return null; + var real = new List<(Entity, Real)>(); + foreach (var root in listed) + if (AsReal(root) is { } value) + { + if (!value.IsFinite) + return null; + real.Add((root, value)); + } + else if (root.Evaled is not Complex { RealPart.IsFinite: true, ImaginaryPart.IsFinite: true }) + return null; + return real; + } + + /// + /// What the expression evaluates to as a real number, or where it is + /// not one. An imaginary part below the downcasting tolerance is the residue of exact + /// cancellation and is read as zero, as downcasting would read it. + /// + private static Real? AsReal(Entity expr) + => expr.Evaled switch + { + Real real => real, + Complex complex when complex.ImaginaryPart.EDecimal.IsFinite + && complex.ImaginaryPart.EDecimal.Abs().LessThan(MathS.Settings.DowncastingTolerance) => complex.RealPart, + _ => null, + }; + + /// Two values that differ by less than the downcasting tolerance are one. + private static bool Same(Real a, Real b) + => a == b || a.IsFinite && b.IsFinite && (a - b).EDecimal.Abs().LessThan(MathS.Settings.DowncastingTolerance); + + /// The set as intervals, or where it is not a union of intervals and points removed. + private static List? Pieces(Entity over) + => over switch + { + SpecialSet.Reals => new List { new Interval(Real.NegativeInfinity, false, Real.PositiveInfinity, false) }, + Interval interval => new List { interval }, + Unionf(var left, var right) => Pieces(left) is { } l && Pieces(right) is { } r ? l.Concat(r).ToList() : null, + SetMinusf(var from, FiniteSet removed) when removed.All(point => AsReal(point) is { IsFinite: true }) + => Pieces(from) is { } pieces ? pieces.SelectMany(piece => CutAt(piece, removed.Select(point => (point, AsReal(point)!)).ToList())).ToList() : null, + _ => null, + }; + + /// The interval cut open at each of the points inside it. + private static IEnumerable CutAt(Interval piece, List<(Entity Root, Real Value)> points) + { + if (AsReal(piece.Left) is not { } left || AsReal(piece.Right) is not { } right) + return new[] { piece }; + var inside = points.Where(point => point.Value.CompareTo(left) > 0 && point.Value.CompareTo(right) < 0) + .OrderBy(point => point.Value).ToList(); + if (inside.Count == 0) + return new[] { piece }; + var cut = new List(); + Entity from = piece.Left; + var fromClosed = piece.LeftClosed; + foreach (var (root, _) in inside) + { + cut.Add(new Interval(from, fromClosed, root, false)); + (from, fromClosed) = (root, false); + } + cut.Add(new Interval(from, fromClosed, piece.Right, piece.RightClosed)); + return cut; + } + + /// + /// Whether the expression is built from the variable, rational constants and the four + /// operations with whole powers no larger than . + /// + private static bool IsRational(Entity f, Variable x) + => f switch + { + _ when !f.ContainsNode(x) => f.Evaled is Rational, + Variable => true, + Sumf(var a, var b) => IsRational(a, x) && IsRational(b, x), + Minusf(var a, var b) => IsRational(a, x) && IsRational(b, x), + Mulf(var a, var b) => IsRational(a, x) && IsRational(b, x), + Divf(var a, var b) => IsRational(a, x) && IsRational(b, x), + Powf(var a, Integer power) when power.EInteger.Abs().CompareTo(EInteger.FromInt32(MaxExponent)) <= 0 => IsRational(a, x), + _ => false, + }; + } +} diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs index eba60c10b..1001b8a52 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs @@ -237,6 +237,13 @@ protected override Entity InnerSimplify(bool isExact) && image.First() is var f && f.Nodes.Count(node => node == Var) == 1 && f.Substitute(Var, overAsInterval).InnerSimplified(isExact) is Set imaged) return imaged; + // A quotient of polynomials the name occurs in more than once, over the + // reals, an interval, or intervals with points taken out, by its critical + // points and its limits: x/(1 + x) over RR \ {-1} is RR \ {1}. + // https://github.com/asc-community/AngouriMath/issues/1409 + if (this is IndexedUnionf && Var is Variable name && body is FiniteSet { Count: 1 } single + && Functions.ImageByCalculus.Of(single.First(), name, over) is { } byCalculus) + return byCalculus; if (over is FiniteSet indices) { if (indices.Count == 0) diff --git a/Sources/Tests/UnitTests/Core/Sets/ImageAndPreImageTest.cs b/Sources/Tests/UnitTests/Core/Sets/ImageAndPreImageTest.cs index 93a0843a7..07c1f18f9 100644 --- a/Sources/Tests/UnitTests/Core/Sets/ImageAndPreImageTest.cs +++ b/Sources/Tests/UnitTests/Core/Sets/ImageAndPreImageTest.cs @@ -36,20 +36,71 @@ public void AnImageIsListedOrAnInterval(string expression, string expected) => Assert.Equal(expected.ToEntity().Evaled, Evaluated(expression)); /// - /// Ex 7.3.4: x^2/(1 + x^2) on RR has image [0, 1). The name occurs - /// twice, so interval arithmetic would overestimate and is not used; the family stays an - /// object and answers membership through the quantifiers where it can. + /// A quotient of polynomials the name occurs in more than once, by its critical points and + /// its limits. Ex 7.3.4, x^2/(1 + x^2) on RR, is [0, 1): 0 is + /// taken at the turning point and 1 only approached. Prob 7.8.8, + /// (2x - 1)/(2x (1 - x)) on (0, 1), is every real. A turning point takes the + /// value an open end only approaches, so x^3 - 3x on (-2, 2) is closed. + /// + [Theory] + [InlineData("image(x^2/(1 + x^2), x in RR)", "[0; 1)")] + [InlineData("image((2 x - 1)/(2 x (1 - x)), x in (0; 1))", "(-oo; +oo)")] + [InlineData("image(x^2 - 2 x, x in [0; 3])", "[-1; 3]")] + [InlineData("image(x^3 - 3 x, x in (-2; 2))", "[-2; 2]")] + [InlineData("image(x^3 - 3 x, x in RR)", "(-oo; +oo)")] + [InlineData("image(x^4 - 2 x^2, x in RR)", "[-1; +oo)")] + [InlineData("image((x^2 + 1)/x, x in (0; +oo))", "[2; +oo)")] + [InlineData("image(x/(1 + x^2), x in RR)", "[-1/2; 1/2]")] + public void AQuotientOfPolynomialsHasItsImageByCalculus(string expression, string expected) + => Assert.Equal(expected.ToEntity().Evaled, Evaluated(expression)); + + /// + /// Across a pole or a removed point the image is a union, compared at points: §7.3.5 + /// Try 1, x/(1 + x) on RR \ {-1}, is RR \ {1}. + /// + [Theory] + [InlineData("image(x/(1 + x), x in RR \\ {-1})", "-1 0 1/2 999/1000 1001/1000 2", "1")] + [InlineData("image(1/x - x, x in RR \\ {0})", "-2 0 1 5", "")] + [InlineData("image(1/(x^2 - 1), x in RR \\ {-1, 1})", "-2 -1 1/2 3", "-1/2 0")] + public void AnImageAcrossAPoleIsAUnion(string expression, string inside, string outside) + { + var image = (Set)Evaluated(expression); + foreach (var (points, expected) in new[] { (inside, true), (outside, false) }) + foreach (var point in points.Split(' ', System.StringSplitOptions.RemoveEmptyEntries)) + { + Assert.True(image.TryContains(point.ToEntity(), out var contains), $"{image} does not decide {point}"); + Assert.Equal(expected, contains); + } + } + + /// + /// Membership in an image is membership in what it evaluates to: 1 is approached by + /// x^2/(1 + x^2) and never taken. /// [Fact] - public void AnImageWithTheNameTwiceStaysAnObject() + public void MembershipInAnImageIsDecided() { - var image = "image(x^2/(1 + x^2), x in RR)".ToEntity(); - Assert.Equal(image, image.Evaled); Assert.Equal(Boolean.True, Evaluated("1/2 in image(x^2/(1 + x^2), x in RR)")); + Assert.Equal(Boolean.False, Evaluated("1 in image(x^2/(1 + x^2), x in RR)")); Assert.Equal(Boolean.False, Evaluated("1/2 in image(9 c / 5 + 32, c in (0; 100))")); Assert.Equal(Boolean.True, Evaluated("100 in image(9 c / 5 + 32, c in (0; 100))")); } + /// + /// An image the calculus cannot read stays the family it is: a function that is not a + /// quotient of polynomials, a derivative of degree five whose zeros the solver does not + /// list, and a symbolic coefficient. + /// + [Theory] + [InlineData("image(x sin(x), x in RR)")] + [InlineData("image(x^6 + x, x in RR)")] + [InlineData("image(a x^2 + x, x in RR)")] + public void AnImageTheCalculusCannotReadStaysAnObject(string expression) + { + var image = expression.ToEntity(); + Assert.Equal(image, image.Evaled); + } + /// Ex 7.3.10: the pre-images of x^2; §7.3.5 rows over the integers. [Theory] [InlineData("preimage(x^2, x in RR, {1})", "{-1, 1}")] diff --git a/Sources/Tests/UnitTests/Core/SurjectivityTest.cs b/Sources/Tests/UnitTests/Core/SurjectivityTest.cs index 313e3d880..8175096f2 100644 --- a/Sources/Tests/UnitTests/Core/SurjectivityTest.cs +++ b/Sources/Tests/UnitTests/Core/SurjectivityTest.cs @@ -16,7 +16,8 @@ namespace AngouriMath.Tests.Core /// forall b in B : exists a in A : f(a) = b -- surjectivity onto B, Def 7.4.1 of the /// reference (Sullivan and Mackey) -- is the statement that B lies in the image of /// A under f, and is decided where the image evaluates: listed over a listed - /// A, an interval by interval arithmetic. The cube is onto the reals because + /// A, an interval by interval arithmetic, and intervals read off the critical points + /// and the limits of a quotient of polynomials. The cube is onto the reals because /// (-oo; +oo)^3 is (-oo; +oo), which needed (-oo)^3 to be -oo /// rather than NaN. /// @@ -33,6 +34,14 @@ public sealed class SurjectivityTest [InlineData("forall b in ZZ : exists a in ZZ : 2 a = b", "False")] [InlineData("forall b in {1, 4, 9} : exists a in {1, 2, 3} : a^2 = b", "True")] [InlineData("forall b in {1, 4, 9, 16} : exists a in {1, 2, 3} : a^2 = b", "False")] + // Images read off the critical points and the limits: a cubic with two turning points is + // onto the reals, x^2/(1 + x^2) is onto [0, 1) and no more, and Sullivan and Mackey's + // §7.3.5 x/(1 + x) is onto every real but 1. + [InlineData("forall b in RR : exists a in RR : a^3 - 3 a = b", "True")] + [InlineData("forall b in RR : exists a in RR : a^2/(1 + a^2) = b", "False")] + [InlineData("forall b in [0; 1) : exists a in RR : a^2/(1 + a^2) = b", "True")] + [InlineData("forall b in RR \\ {1} : exists a in RR \\ {-1} : a/(1 + a) = b", "True")] + [InlineData("forall b in RR : exists a in RR \\ {-1} : a/(1 + a) = b", "False")] public void SurjectivityIsTheImageCoveringTheCodomain(string statement, string expected) => Assert.Equal(expected.ToEntity(), statement.ToEntity().Evaled);