diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index caec10ebd..d38cc9375 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -240,6 +240,29 @@ dropped ([#2458](https://github.com/asc-community/AngouriMath/issues/2458)). --- +### A product over a set: `product(f, x in S)` + +**Not silent: what was refused now parses.** `product` took a range and nothing else, so `product(f, x in S)` threw +`FunctionArgumentCountException`. It is now the node `ProductOverSetf`, the product of `f` over the members of `S`, each +counted once, built by `MathS.Product(f, x, S)` and printed `\prod_{x \in S} f`. Its factors are multiplied out exactly +where `sum(f, x in S)` adds its terms up, and it is left as written where the sum is; the product over no members is +`1`. The range form is unchanged +([#2449](https://github.com/asc-community/AngouriMath/issues/2449)). + +**Silent, for the sum too:** a set of roots with listed members taken out, `{ w : p(w) = 0 } \ { m }`, is now read, +since the product rule over a set writes one. A member taken out is found as it was written; a number whose value is +none of the roots takes nothing out; anything else, a symbol among them, leaves the sum as written. + +| Input | Was (2.7.0) | Now | +|---|---|---| +| `"product(p, p in PP /\\ [1; 30])".ToEntity().Simplify()` | throws `FunctionArgumentCountException` | `6469693230` | +| `"product(1 - 1/p^2, p in {2, 3, 5})".ToEntity().Simplify()` | throws `FunctionArgumentCountException` | `16/25` | +| `"product(x, x in {})".ToEntity().Simplify()` | throws `FunctionArgumentCountException` | `1` | +| `"product(x, x in {a, b})".ToEntity().Simplify()` | throws `FunctionArgumentCountException` | `product(x, x in { a, b })`, left | +| `"product(w + y, w in { w : w^3 + w + 1 = 0 })".ToEntity().Differentiate("y")` at `y = 1`, `.Evaled` | throws `FunctionArgumentCountException` | `4` | +| `"sum(x, x in { w : w^2 - 2 = 0 } \\ { sqrt(2) })".ToEntity().Simplify()` | `sum(x, x in { w : w ^ 2 - 2 = 0 } \ { sqrt(2) })` | `-sqrt(2)` | +| `"sum(x, x in { w : w^2 - 3w + 2 = 0 } \\ { 1 })".ToEntity().Simplify()` | `sum(x, x in { w : w ^ 2 - 3 * w + 2 = 0 } \ { 1 })` | `2` | + ### A system row that is not a solution declines the system **Silent: a wrong row is now no answer.** With `P + Q sqrt(2) = (1 + sqrt(2))^70`, the coefficient `P - Q y` is diff --git a/Sources/.editorconfig b/Sources/.editorconfig index 8235ea3c1..24f093e7a 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -1114,3 +1114,6 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [Tests/UnitTests/Core/ANumberEvaluatesToItselfTest.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/Calculus/ProductOverSetTest.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/Convenience/MathS.cs b/Sources/AngouriMath/Convenience/MathS.cs index dad44859b..4545cfbe5 100644 --- a/Sources/AngouriMath/Convenience/MathS.cs +++ b/Sources/AngouriMath/Convenience/MathS.cs @@ -7899,6 +7899,35 @@ public static Entity Sum(Entity expr, Entity var, Entity from, Entity to) public static Entity Sum(Entity expr, Entity var, Entity over) => new SumOverSetf(expr, var, over); + /// + /// The product of over the members of as + /// ranges over it, each member counted once: written + /// product(expr, var in over). The product over no members is 1. + /// + /// The factor, as a function of . + /// The name that ranges over the set, bound by the product. + /// The set. + /// + /// The factors multiplied out where would add its + /// terms up: a listed set of numbers, or roots of a polynomial that are rational, roots of + /// a quadratic or roots of a binomial. Left as written otherwise. + /// + /// #2449 + /// + /// + /// using System; + /// using static AngouriMath.MathS; + /// + /// Console.WriteLine(Product("p", "p", "PP /\\ [1; 10]").Simplify()); + /// + /// Prints + /// + /// 210 + /// + /// + public static Entity Product(Entity expr, Entity var, Entity over) + => new ProductOverSetf(expr, var, over); + /// /// The largest value takes as ranges over /// , written max(expr, var in over). Answered over a finite diff --git a/Sources/AngouriMath/Core/Antlr/AngouriMath.g b/Sources/AngouriMath/Core/Antlr/AngouriMath.g index 543de7d88..1bf511ca4 100644 --- a/Sources/AngouriMath/Core/Antlr/AngouriMath.g +++ b/Sources/AngouriMath/Core/Antlr/AngouriMath.g @@ -597,7 +597,7 @@ atom returns[Entity value] | 'limitleft(' args = function_arguments ')' { Assert("limitleft", 3, $args.list.Count); $value = MathS.Limit($args.list[0], $args.list[1], $args.list[2], AngouriMath.Core.ApproachFrom.Left); } | 'limitright(' args = function_arguments ')' { Assert("limitright", 3, $args.list.Count); $value = MathS.Limit($args.list[0], $args.list[1], $args.list[2], AngouriMath.Core.ApproachFrom.Right); } | 'sum(' args = function_arguments ')' { if ($args.list.Count == 2 && AngouriMath.Functions.ExtremumOverSet.AsRange($args.list[1]) is var (sumVar, sumOver)) $value = MathS.Sum($args.list[0], sumVar, sumOver); else { Assert("sum", 4, $args.list.Count); $value = MathS.Sum($args.list[0], $args.list[1], $args.list[2], $args.list[3]); } } - | 'product(' args = function_arguments ')' { Assert("product", 4, $args.list.Count); $value = MathS.Product($args.list[0], $args.list[1], $args.list[2], $args.list[3]); } + | 'product(' args = function_arguments ')' { if ($args.list.Count == 2 && AngouriMath.Functions.ExtremumOverSet.AsRange($args.list[1]) is var (productVar, productOver)) $value = MathS.Product($args.list[0], productVar, productOver); else { Assert("product", 4, $args.list.Count); $value = MathS.Product($args.list[0], $args.list[1], $args.list[2], $args.list[3]); } } | 'signum(' args = function_arguments ')' { Assert("signum", 1, $args.list.Count); $value = MathS.Signum($args.list[0]); } | 'sgn(' args = function_arguments ')' { Assert("sgn", 1, $args.list.Count); $value = MathS.Signum($args.list[0]); } | 'sign(' args = function_arguments ')' { Assert("sign", 1, $args.list.Count); $value = MathS.Signum($args.list[0]); } diff --git a/Sources/AngouriMath/Core/Antlr/AngouriMathParser.cs b/Sources/AngouriMath/Core/Antlr/AngouriMathParser.cs index 45e0a6fb5..4e4e1a545 100644 --- a/Sources/AngouriMath/Core/Antlr/AngouriMathParser.cs +++ b/Sources/AngouriMath/Core/Antlr/AngouriMathParser.cs @@ -4835,7 +4835,7 @@ public AtomContext atom() { _localctx.args = function_arguments(); State = 932; Match(T__34); - Assert("product", 4, _localctx.args.list.Count); _localctx.value = MathS.Product(_localctx.args.list[0], _localctx.args.list[1], _localctx.args.list[2], _localctx.args.list[3]); + if (_localctx.args.list.Count == 2 && AngouriMath.Functions.ExtremumOverSet.AsRange(_localctx.args.list[1]) is var (productVar, productOver)) _localctx.value = MathS.Product(_localctx.args.list[0], productVar, productOver); else { Assert("product", 4, _localctx.args.list.Count); _localctx.value = MathS.Product(_localctx.args.list[0], _localctx.args.list[1], _localctx.args.list[2], _localctx.args.list[3]); } } break; case 101: diff --git a/Sources/AngouriMath/Core/Domains.Classes.cs b/Sources/AngouriMath/Core/Domains.Classes.cs index 59f83da27..feca54eaa 100644 --- a/Sources/AngouriMath/Core/Domains.Classes.cs +++ b/Sources/AngouriMath/Core/Domains.Classes.cs @@ -400,6 +400,14 @@ partial record SumOverSetf internal override Domain DefaultCodomain => Domain.Complex; } + partial record ProductOverSetf + { + /// + public override Domain Codomain { get; protected init; } = Domain.Complex; + /// + internal override Domain DefaultCodomain => Domain.Complex; + } + partial record Maximumf { /// diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Calculus.Classes.cs b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Calculus.Classes.cs index bf85c70b2..4cc838e09 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Calculus.Classes.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Calculus.Classes.cs @@ -142,6 +142,27 @@ public override Entity Replace(Func func) => protected override Entity[] InitDirectChildren() => new[] { Expression, Var, Over }; } + /// + /// A product over a set: product(f(x), x in S) is the product of f(x) over + /// the members x of S, each counted once. See , which + /// it mirrors: product(p, p in PP /\ [1; 30]) is the primorial of 29. + /// https://github.com/asc-community/AngouriMath/issues/2449 + /// + public sealed partial record ProductOverSetf(Entity Expression, Entity Var, Entity Over) : CalculusOperator(Expression, Var) + { + /// The set the variable ranges over. + public Entity Over { get; init; } = Binding.Of(Var).In(Over); + + private ProductOverSetf New(Entity expression, Entity var, Entity over) => + ReferenceEquals(Expression, expression) && ReferenceEquals(Var, var) && ReferenceEquals(Over, over) + ? this : new(expression, var, over) { Codomain = Codomain }; + /// + public override Entity Replace(Func func) => + func(New(Expression.Replace(func), Var, Over.Replace(func))); + /// + protected override Entity[] InitDirectChildren() => new[] { Expression, Var, Over }; + } + /// /// A node of limit /// diff --git a/Sources/AngouriMath/Core/Entity/Entity.Definition.cs b/Sources/AngouriMath/Core/Entity/Entity.Definition.cs index 7a0edf6f3..4e84a7a53 100644 --- a/Sources/AngouriMath/Core/Entity/Entity.Definition.cs +++ b/Sources/AngouriMath/Core/Entity/Entity.Definition.cs @@ -697,6 +697,7 @@ public IReadOnlyList Vars // A sum over a set binds the name that ranges over the set: // sum(w * a, w in { w : w^2 = 2 }) is a function of a alone. SumOverSetf(var body, var bound, var over) => BoundBy(bound, body, over), + ProductOverSetf(var body, var bound, var over) => BoundBy(bound, body, over), // An extremum over a set binds the variable that ranges over the set: // max(t^2 + a, t in [0; 1]) is a function of a alone. Maximumf(var body, var bound, var over) => BoundBy(bound, body, over), diff --git a/Sources/AngouriMath/Core/Serialization/Entity.Serialization.cs b/Sources/AngouriMath/Core/Serialization/Entity.Serialization.cs index 7d80a38df..22955baa6 100644 --- a/Sources/AngouriMath/Core/Serialization/Entity.Serialization.cs +++ b/Sources/AngouriMath/Core/Serialization/Entity.Serialization.cs @@ -159,6 +159,7 @@ [EntityJsonConverter] partial record SpecialSet [EntityJsonConverter] partial record Summationf; [EntityJsonConverter] partial record Maximumf; [EntityJsonConverter] partial record SumOverSetf; + [EntityJsonConverter] partial record ProductOverSetf; [EntityJsonConverter] partial record Minimumf; [EntityJsonConverter] partial record Argmaxf; [EntityJsonConverter] partial record Argminf; diff --git a/Sources/AngouriMath/Docs/Usage/Syntax.md b/Sources/AngouriMath/Docs/Usage/Syntax.md index 23ef6c71e..554b1f951 100644 --- a/Sources/AngouriMath/Docs/Usage/Syntax.md +++ b/Sources/AngouriMath/Docs/Usage/Syntax.md @@ -470,7 +470,9 @@ A whole `a >= 1` is elementary, `gamma(3, x)` being `2 * e ^ (-x) * (1 + x + x ^ **Calculus** — `derivative(expr, var, order)`, `integral(expr, var)`, `integral(expr, var, from, to)`, `limit(expr, var, dest)`, `limitleft(...)`, `limitright(...)`; -`sum(expr, var in set)` for a sum over a set; `max(expr, var in set)` and `min` for the extremum of +`sum(expr, var in set)` for a sum over a set and `product(expr, var in set)` for a product over one, +each member counted once (`product(p, p in PP /\ [1; 30])` is `6469693230`, the empty product `1`); +`max(expr, var in set)` and `min` for the extremum of an expression over a set, `argmax` and `argmin` for the set of points where it is taken — `max(a, b)` of two values is still the larger. `min(S)` with one argument that is a set is its least member, `min(x, x in S)`, and the range diff --git a/Sources/AngouriMath/Functions/Algebra/SumOverSet.cs b/Sources/AngouriMath/Functions/Algebra/SumOverSet.cs index a1ea708d9..c73ce6e85 100644 --- a/Sources/AngouriMath/Functions/Algebra/SumOverSet.cs +++ b/Sources/AngouriMath/Functions/Algebra/SumOverSet.cs @@ -44,10 +44,12 @@ namespace AngouriMath.Functions internal static class SumOverSet { /// - /// The sum, or where the members of the set are not known or not - /// finitely many. + /// The sum, or with the product, or where + /// the members of the set are not known or not finitely many. A product over a set needs + /// its members known and distinct exactly as a sum does, and over no members it is 1 as + /// the sum is 0. https://github.com/asc-community/AngouriMath/issues/2449 /// - internal static Entity? Value(Entity expression, Entity var, Entity over, bool isExact) + internal static Entity? Value(Entity expression, Entity var, Entity over, bool isExact, bool product = false) { if (var is not Variable x || over.InnerSimplified is not Set set) return null; @@ -60,9 +62,9 @@ internal static class SumOverSet foreach (var member in members) { var term = expression.Substitute(x, member); - sum = sum is null ? term : sum + term; + sum = sum is null ? term : product ? sum * term : sum + term; } - sum ??= Integer.Zero; + sum ??= product ? Integer.One : Integer.Zero; return isExact ? sum.InnerSimplified : sum.Evaled; } @@ -79,9 +81,40 @@ internal static class SumOverSet ConditionalSet { Var: Variable w } builder when builder.DeclaredMembership is (Set universe, Equalsf(var left, var right)) => Roots(left - right, w) is { } roots ? Within(roots, universe) : null, ConditionalSet { Var: Variable w, Predicate: Equalsf(var left, var right) } => Roots(left - right, w), + SetMinusf(Set from, FiniteSet removed) => Members(from) is { } members ? Without(members, removed) : null, _ => null, }; + /// + /// without the elements of , or + /// where it is not decided whether one of those is a member. An + /// element written as a member is that member; one whose value differs from every + /// member's is none of them, compared as compares; and one that + /// agrees in value with a member it is not written as is undecided. The product rule over + /// a set writes S \ { m } with m a member of S, and a member is + /// substituted for m as it was listed, so it is found as written. + /// https://github.com/asc-community/AngouriMath/issues/2449 + /// + private static IReadOnlyList? Without(IReadOnlyList members, FiniteSet removed) + { + var kept = new List(members); + foreach (var element in removed.Elements) + { + var at = kept.IndexOf(element); + if (at >= 0) + { + kept.RemoveAt(at); + continue; + } + if (element.Evaled is not Complex value || !value.IsFinite) + return null; + foreach (var member in kept) + if (member.Evaled is not Complex seen || seen == value) + return null; + } + return kept; + } + /// /// The members of that are in , or /// where that is not decided for one of them. @@ -162,6 +195,7 @@ internal static class SumOverSet ConditionalSet { Var: Variable w } builder when builder.DeclaredMembership is (Set universe, Equalsf(var left, var right)) => NumericRoots(left - right, w) is { } roots ? Within(roots, universe) : null, ConditionalSet { Var: Variable w, Predicate: Equalsf(var left, var right) } => NumericRoots(left - right, w), + SetMinusf(Set from, FiniteSet removed) => NumericMembers(from) is { } members ? Without(members, removed) : null, _ => null, }; diff --git a/Sources/AngouriMath/Functions/Compilation/Binders.cs b/Sources/AngouriMath/Functions/Compilation/Binders.cs index 51e22a130..ef90cd019 100644 --- a/Sources/AngouriMath/Functions/Compilation/Binders.cs +++ b/Sources/AngouriMath/Functions/Compilation/Binders.cs @@ -40,6 +40,7 @@ internal static void Check(Entity expression) Summationf => "a sum", Productf => "a product", SumOverSetf => "a sum over a set", + ProductOverSetf => "a product over a set", Maximumf => "a maximum over a set", Minimumf => "a minimum over a set", Argmaxf => "the set of points where a maximum is taken", diff --git a/Sources/AngouriMath/Functions/Continuous/Differentiation.cs b/Sources/AngouriMath/Functions/Continuous/Differentiation.cs index 66ad68fa6..941cf76f1 100644 --- a/Sources/AngouriMath/Functions/Continuous/Differentiation.cs +++ b/Sources/AngouriMath/Functions/Continuous/Differentiation.cs @@ -606,6 +606,29 @@ protected override Entity InnerDifferentiate(Variable variable) => : New(Expression.DerivativeOver(variable), Var, Over); } + partial record ProductOverSetf + { + /// + /// + /// The product rule over finitely many factors, where the set does not depend on the + /// variable: each factor differentiated in turn, times the product of the others, + /// sum(f'(m) product(f(n), n in S \ { m }), m in S). It holds where a factor is + /// zero, which product(f) sum(f'/f) does not. Zero in the bound name. + /// https://github.com/asc-community/AngouriMath/issues/2449 + /// + protected override Entity InnerDifferentiate(Variable variable) + { + if (Var == variable) + return Integer.Zero; + if (Over.ContainsNode(variable) || Var is not Variable member) + return base.InnerDifferentiate(variable); + var other = Variable.CreateUnique(this + variable, member.Name); + var others = new ProductOverSetf(Expression.Substitute(member, other), other, + new Set.SetMinusf(Over, new Set.FiniteSet(member))); + return new SumOverSetf(Expression.DerivativeOver(variable) * others, member, Over); + } + } + partial record Limitf { /// diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/InvertNode.Classes.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/InvertNode.Classes.cs index 90dc0fea5..b80504dde 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/InvertNode.Classes.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/InvertNode.Classes.cs @@ -578,6 +578,13 @@ partial record SumOverSetf null; } + partial record ProductOverSetf + { + // The unknown sits under a binder; see Summationf below. + private protected override IEnumerable? InvertNode(Entity value, Entity x) => + null; + } + partial record Maximumf { // The unknown sits under a binder; see Summationf below. diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Calculus.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Calculus.Classes.cs index 75127ed63..df086e646 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Calculus.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Calculus.Classes.cs @@ -233,6 +233,25 @@ protected override Entity InnerSimplify(bool isExact) ?? New(Expression.InnerSimplified, Var, Over.InnerSimplified); } + partial record ProductOverSetf + { + /// + /// A product over a set is a well-formed expression whatever the set, as a sum over a set + /// is; multiplying its factors out is an evaluation, not a claim about where it is defined. + /// + private protected override Entity IntrinsicCondition => Boolean.True; + /// + /// + /// The factors are multiplied out where the sum's terms would be added up -- a listed set + /// of numbers, distinct by value, and the roots of a polynomial the solver writes all of + /// -- and the product is left as written, in its simplest parts, where they would not. + /// https://github.com/asc-community/AngouriMath/issues/2449 + /// + protected override Entity InnerSimplify(bool isExact) + => Functions.SumOverSet.Value(Expression, Var, Over, isExact, product: true) + ?? New(Expression.InnerSimplified, Var, Over.InnerSimplified); + } + // TODO: rewrite this part too public partial record Summationf { diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs index cf8c6f31e..739d69d86 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs @@ -133,6 +133,7 @@ private static Entity ScopedToItsBinder(Entity binder, Entity condition) (Entity Name, Entity? Range)? scope = binder switch { SumOverSetf(_, var name, var over) => (name, over), + ProductOverSetf(_, var name, var over) => (name, over), Maximumf(_, var name, var over) => (name, over), Minimumf(_, var name, var over) => (name, over), Argmaxf(_, var name, var over) => (name, over), diff --git a/Sources/AngouriMath/Functions/Output/Latex/Latex.Calculus.Classes.cs b/Sources/AngouriMath/Functions/Output/Latex/Latex.Calculus.Classes.cs index 2bd05f539..436679cc7 100644 --- a/Sources/AngouriMath/Functions/Output/Latex/Latex.Calculus.Classes.cs +++ b/Sources/AngouriMath/Functions/Output/Latex/Latex.Calculus.Classes.cs @@ -74,6 +74,14 @@ private protected override string LatexizeNode() => + Expression.Latexize(Expression.Priority < Priority.Sum); } + public partial record ProductOverSetf + { + /// + private protected override string LatexizeNode() => + @"\prod_{" + Var.Latexize() + @" \in " + Over.Latexize() + "} " + + Expression.Latexize(Expression.Priority < Priority.Mul); + } + public partial record Maximumf { /// diff --git a/Sources/AngouriMath/Functions/Output/ToString/ToString.Calculus.Classes.cs b/Sources/AngouriMath/Functions/Output/ToString/ToString.Calculus.Classes.cs index 5962c76d2..f704b6afb 100644 --- a/Sources/AngouriMath/Functions/Output/ToString/ToString.Calculus.Classes.cs +++ b/Sources/AngouriMath/Functions/Output/ToString/ToString.Calculus.Classes.cs @@ -45,6 +45,15 @@ private protected override string StringizeNode() => public override string ToString() => Stringize(); } + public partial record ProductOverSetf + { + /// + private protected override string StringizeNode() => + $"product({Expression.Stringize()}, {Var.Stringize()} in {Over.Stringize()})"; + /// + public override string ToString() => Stringize(); + } + public partial record Maximumf { /// diff --git a/Sources/AngouriMath/Functions/Output/ToSympy/ToSympy.Calculus.Classes.cs b/Sources/AngouriMath/Functions/Output/ToSympy/ToSympy.Calculus.Classes.cs index c98eb5f8e..7378958a2 100644 --- a/Sources/AngouriMath/Functions/Output/ToSympy/ToSympy.Calculus.Classes.cs +++ b/Sources/AngouriMath/Functions/Output/ToSympy/ToSympy.Calculus.Classes.cs @@ -35,6 +35,20 @@ public partial record SumOverSetf }; } + public partial record ProductOverSetf + { + // SymPy has no RootProduct, so the roots go over as the CRootOf roots of the square-free + // part, each once, as a set counts them. + internal override string ToSymPy() => Over switch + { + Set.FiniteSet finite => + $"sympy.Mul(*[({Expression.ToSymPy()}).subs({Var.ToSymPy()}, member) for member in [{string.Join(", ", finite.Elements.Select(static e => e.ToSymPy()))}]])", + Set.ConditionalSet { Var: Variable w, Predicate: Equalsf(var left, var right) } when w == Var => + $"sympy.Mul(*[({Expression.ToSymPy()}).subs({Var.ToSymPy()}, member) for member in sympy.Poly(sympy.sqf_part(sympy.Poly({(left - right).ToSymPy()}, {Var.ToSymPy()})), {Var.ToSymPy()}).all_roots()])", + _ => throw new NotSufficientlySupportedException("SymPy has no product over a set; a listed set or the roots of a polynomial can be exported"), + }; + } + public partial record Maximumf { internal override string ToSymPy() => diff --git a/Sources/AngouriMath/Functions/Substitute.cs b/Sources/AngouriMath/Functions/Substitute.cs index 07e3c4ab8..f3f87a518 100644 --- a/Sources/AngouriMath/Functions/Substitute.cs +++ b/Sources/AngouriMath/Functions/Substitute.cs @@ -825,6 +825,19 @@ public override Entity Substitute(Entity x, Entity value) } } + partial record ProductOverSetf + { + /// + // The variable is bound; renamed first, as a sum over a set's is. + public override Entity Substitute(Entity x, Entity value) + { + if (this == x) + return value; + var (renamed, boundName) = SubstituteUnderABinder(Expression, Var, x, value); + return New(renamed, boundName, Over.Substitute(x, value)); + } + } + partial record Maximumf { /// diff --git a/Sources/AngouriMath/Functions/TreeAnalyzer/Sort.Classes.cs b/Sources/AngouriMath/Functions/TreeAnalyzer/Sort.Classes.cs index a2c0b276b..355487d19 100644 --- a/Sources/AngouriMath/Functions/TreeAnalyzer/Sort.Classes.cs +++ b/Sources/AngouriMath/Functions/TreeAnalyzer/Sort.Classes.cs @@ -262,6 +262,11 @@ public partial record SumOverSetf private protected override string SortHashName(SortLevel level) => "sumoversetf_"; } + public partial record ProductOverSetf + { + private protected override string SortHashName(SortLevel level) => "productoversetf_"; + } + public partial record Maximumf { private protected override string SortHashName(SortLevel level) => "maximumf_"; diff --git a/Sources/AngouriMath/Numerics/PreciseEvaluation.cs b/Sources/AngouriMath/Numerics/PreciseEvaluation.cs index 37fdcb4ec..4dbb93526 100644 --- a/Sources/AngouriMath/Numerics/PreciseEvaluation.cs +++ b/Sources/AngouriMath/Numerics/PreciseEvaluation.cs @@ -608,6 +608,10 @@ PreciseComplexInterval AtTheOrder(EDecimal re, EDecimal im) // https://github.com/asc-community/AngouriMath/issues/1285 case SumOverSetf(var summand, Variable name, Set.ConditionalSet { Var: Variable w, Predicate: Equalsf(var left, var right) }): return OverTheRoots(summand, name, left - right, w); + // And a product over them the same way, the factors multiplied. + // https://github.com/asc-community/AngouriMath/issues/2449 + case ProductOverSetf(var factor, Variable name, Set.ConditionalSet { Var: Variable w, Predicate: Equalsf(var left, var right) }): + return OverTheRoots(factor, name, left - right, w, product: true); default: return undefined; } @@ -615,20 +619,22 @@ PreciseComplexInterval AtTheOrder(EDecimal re, EDecimal im) /// /// added up over the roots of in - /// , taken by in turn; undefined where a root - /// cannot be enclosed apart from the others. + /// , taken by in turn, or with + /// multiplied; undefined where a root cannot be enclosed apart + /// from the others. /// - private PreciseComplexInterval OverTheRoots(Entity summand, Variable name, Entity polynomial, Variable w) + private PreciseComplexInterval OverTheRoots(Entity summand, Variable name, Entity polynomial, Variable w, bool product = false) { if (RootsEnclosed(polynomial, w) is not { } roots) return undefined; - var total = Real(PreciseInterval.Exactly(EDecimal.Zero)); + var total = Real(PreciseInterval.Exactly(product ? EDecimal.One : EDecimal.Zero)); foreach (var root in roots) { bound ??= new(); var own = Variable.CreateTemp(summand.Vars.Concat(bound.Keys).Append(name)); bound[own] = root; - total = Add(total, Evaluate(summand.Substitute(name, own))); + var term = Evaluate(summand.Substitute(name, own)); + total = product ? Multiply(total, term) : Add(total, term); } return total; } diff --git a/Sources/Tests/UnitTests/Calculus/ProductOverSetTest.cs b/Sources/Tests/UnitTests/Calculus/ProductOverSetTest.cs new file mode 100644 index 000000000..79af44b18 --- /dev/null +++ b/Sources/Tests/UnitTests/Calculus/ProductOverSetTest.cs @@ -0,0 +1,167 @@ +// +// 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; +using AngouriMath.Core.Exceptions; +using AngouriMath.Extensions; +using PeterO.Numbers; +using Xunit; +using static AngouriMath.Entity; +using static AngouriMath.Entity.Number; + +namespace AngouriMath.Tests.Calculus +{ + /// + /// product(f(x), x in S): the product of an expression over the members of a set, each + /// counted once, as a binder that mirrors the sum over a set. + /// https://github.com/asc-community/AngouriMath/issues/2449 + /// + [Trait("Area", "Calculus")] + public sealed class ProductOverSetTest + { + [Fact] + public void ItIsWrittenAsItIsRead() + { + var product = "product(x^2, x in {1, 2, 3})".ToEntity(); + Assert.IsType(product); + Assert.Equal("product(x ^ 2, x in { 1, 2, 3 })", product.Stringize()); + Assert.Equal(product, product.Stringize().ToEntity()); + Assert.Equal(product, MathS.Product("x^2", "x", "{1, 2, 3}")); + } + + /// The range form keeps its meaning, and two arguments that are not a range are the error they were. + [Fact] + public void TheRangeFormIsUnchanged() + { + Assert.IsType("product(k, k, 1, 5)".ToEntity()); + Assert.Equal(Integer.Create(120), "product(k, k, 1, 5)".ToEntity().Simplify()); + Assert.ThrowsAny(() => "product(x, y)".ToEntity()); + } + + /// + /// The primes up to 30 multiply to the primorial 29# = 6469693230, and the Euler factors + /// at 2, 3 and 5 of 1/zeta(2) to (3/4)(8/9)(24/25) = 16/25. The empty product is 1. + /// + [Theory] + [InlineData("product(p, p in PP /\\ [1; 30])", "6469693230")] + [InlineData("product(1 - 1/p^2, p in {2, 3, 5})", "16/25")] + [InlineData("product(x, x in {})", "1")] + [InlineData("product(7, x in {1, 2, 3})", "343")] + // An integer range is listed, so the set form agrees with the range form. + [InlineData("product(k, k in ZZ intersect [1; 6])", "720")] + // The product of the roots of a monic polynomial is (-1)^n times its constant term. + [InlineData("product(w, w in { w : w^2 - 3 = 0 })", "-3")] + [InlineData("product(w - 1, w in { w : w^2 - 3w + 2 = 0 })", "0")] + [InlineData("product(w^2, w in { w in RR : w^4 - 1 = 0 })", "1")] + // A set counts a member once, so a double root is one factor. + [InlineData("product(w, w in { w : (w - 1)^2 (w - 2) = 0 })", "2")] + public void TheFactorsAreMultipliedOut(string product, string value) + => Assert.Equal(value.ToEntity(), product.ToEntity().Simplify()); + + [Fact] + public void TheEmptyProductIsOneAsTheEmptySumIsZero() + { + Assert.Equal(Integer.One, "product(x, x in {})".ToEntity().Evaled); + Assert.Equal(Integer.Zero, "sum(x, x in {})".ToEntity().Evaled); + } + + /// Left as written wherever the sum over the same set is. + [Theory] + [InlineData("x, x in {a, b}")] + [InlineData("x, x in [0; 1]")] + [InlineData("k, k in ZZ")] + [InlineData("p, p in PP")] + [InlineData("w, w in { w : w^5 + w + 3 = 0 }")] + [InlineData("w^2 + 1, w in { w : w^3 + w + 1 = 0 }")] + public void WhatTheSumLeavesAsWrittenTheProductDoesToo(string arguments) + { + Assert.IsType($"sum({arguments})".ToEntity().InnerSimplified); + Assert.IsType($"product({arguments})".ToEntity().InnerSimplified); + } + + /// + /// Evaluated to a number over roots the solver cannot write: the roots of + /// w^5 + w + 3 multiply to -3, and over the roots of p = w^3 + w + 1, + /// w^2 + 1 = (w - i)(w + i) multiplies to p(i) p(-i) = 1. + /// + [Theory] + [InlineData("product(w, w in { w : w^5 + w + 3 = 0 })", "-3")] + [InlineData("product(w^2 + 1, w in { w : w^3 + w + 1 = 0 })", "1")] + public void NumericallyOverRootsTheSolverCannotWrite(string product, string exact) + => AssertClose(exact.ToEntity().Evaled, product.ToEntity().Evaled); + + /// The name ranges over the set, so the product is not a function of it. + [Fact] + public void TheNameIsBound() + { + var product = "product(w * a, w in { w : w^5 + w + 3 = 0 })".ToEntity(); + Assert.Equal(new[] { MathS.Var("a") }, product.FreeVariables); + Assert.Equal(product, product.Substitute("w", 5)); + Assert.Equal("product(w * 2, w in { w : w ^ 5 + w + 3 = 0 })".ToEntity(), product.Substitute("a", 2)); + } + + /// + /// The product rule, which holds where a factor is zero: over { 1, 2, 3 } the + /// derivative of (y + 1)(y + 2)(y + 3), 26 at 1; over the roots of + /// w^3 + w + 1 the product of w + y is y^3 + y - 1, whose derivative + /// is 4 at 1; and zero in the bound name. + /// + [Theory] + [InlineData("product(w + y, w in {1, 2, 3})", "(y + 1)(y + 2)(y + 3)")] + [InlineData("product(w + y, w in { w : w^2 - 2 = 0 })", "y^2 - 2")] + [InlineData("product(w + y, w in { w : w^3 + w + 1 = 0 })", "y^3 + y - 1")] + [InlineData("product(w - y, w in {1, 2})", "(1 - y)(2 - y)")] + public void ItIsDifferentiatedByTheProductRule(string product, string expanded) + { + var derivative = product.ToEntity().Differentiate("y"); + foreach (var at in new[] { "1", "2", "-3/2" }) + AssertClose(expanded.ToEntity().Differentiate("y").Substitute("y", at).Evaled, + derivative.Substitute("y", at).Evaled); + Assert.Equal(Integer.Zero, product.ToEntity().Differentiate("w")); + } + + [Fact] + public void ItsConditionIsRequiredAtEveryMember() + { + var condition = "product(1/(w - x), w in {1, 2})".ToEntity().DomainCondition; + Assert.DoesNotContain(condition.Vars, v => v.Name == "w"); + Assert.Equal(MathS.Boolean.False, condition.Substitute("x", 2).Simplify()); + Assert.Equal(MathS.Boolean.True, condition.Substitute("x", 3).Simplify()); + } + + [Fact] + public void ItPrintsAsAProductUnderItsRange() + { + Assert.Equal(@"\prod_{x \in \left\{ 1, 2, 3 \right\}} {x}^{2}", "product(x^2, x in {1, 2, 3})".ToEntity().Latexize()); + Assert.Equal(@"\prod_{x \in S} \left(x+1\right)", "product(x + 1, x in S)".ToEntity().Latexize()); + } + + /// + /// A member taken out of a set of roots is found as it was written, and a number that is + /// none of them takes nothing out: the product rule writes S \ { m }. + /// + [Theory] + [InlineData("sum(x, x in { w : w^2 - 2 = 0 } \\ { sqrt(2) })", "-sqrt(2)")] + [InlineData("sum(x, x in { w : w^2 - 3w + 2 = 0 } \\ { 1 })", "2")] + [InlineData("product(x, x in { w : w^2 - 3w + 2 = 0 } \\ { 5 })", "2")] + public void AMemberTakenOutOfASetOfRootsIsFound(string expression, string value) + => Assert.Equal(value.ToEntity(), expression.ToEntity().Simplify()); + + [Fact] + public void ASymbolTakenOutIsUndecided() + => Assert.IsType("sum(x, x in { w : w^2 - 3w + 2 = 0 } \\ { a })".ToEntity().Simplify()); + + private static void AssertClose(Entity expected, Entity actual) + { + var e = Assert.IsAssignableFrom(expected); + var a = Assert.IsAssignableFrom(actual); + var tolerance = EDecimal.FromString("1E-50"); + Assert.True(e.RealPart.EDecimal.Subtract(a.RealPart.EDecimal).Abs().CompareTo(tolerance) < 0, $"{a} is not {e}"); + Assert.True(e.ImaginaryPart.EDecimal.Subtract(a.ImaginaryPart.EDecimal).Abs().CompareTo(tolerance) < 0, $"{a} is not {e}"); + } + } +} diff --git a/Sources/Tests/UnitTests/Common/BinderCompilationRefusalTest.cs b/Sources/Tests/UnitTests/Common/BinderCompilationRefusalTest.cs index 025606919..2fbc0ea70 100644 --- a/Sources/Tests/UnitTests/Common/BinderCompilationRefusalTest.cs +++ b/Sources/Tests/UnitTests/Common/BinderCompilationRefusalTest.cs @@ -30,6 +30,7 @@ public sealed class BinderCompilationRefusalTest [InlineData("sum(x^k, k, 1, 3)", "sum(x ^ k, k, 1, 3)")] [InlineData("product(x + k, k, 1, 3)", "product(x + k, k, 1, 3)")] [InlineData("sum(x k, k in {1, 2})", "sum(x * k, k in { 1, 2 })")] + [InlineData("product(x k, k in {1, 2})", "product(x * k, k in { 1, 2 })")] [InlineData("max(x k, k in {1, 2})", "max(x * k, k in { 1, 2 })")] [InlineData("min(x k, k in {1, 2})", "min(x * k, k in { 1, 2 })")] [InlineData("argmax(x k, k in {1, 2})", "argmax(x * k, k in { 1, 2 })")] diff --git a/Sources/Tests/UnitTests/Common/PublicApi.txt b/Sources/Tests/UnitTests/Common/PublicApi.txt index 59f79c929..8239698fb 100644 --- a/Sources/Tests/UnitTests/Common/PublicApi.txt +++ b/Sources/Tests/UnitTests/Common/PublicApi.txt @@ -2439,6 +2439,25 @@ AngouriMath.Entity+Primef.ToString() : System.String AngouriMath.Entity+Primef.ctor(AngouriMath.Entity) AngouriMath.Entity+Primef.op_Equality(AngouriMath.Entity+Primef, AngouriMath.Entity+Primef) : System.Boolean AngouriMath.Entity+Primef.op_Inequality(AngouriMath.Entity+Primef, AngouriMath.Entity+Primef) : System.Boolean +AngouriMath.Entity+ProductOverSetf.$() : AngouriMath.Entity+ProductOverSetf +AngouriMath.Entity+ProductOverSetf.Codomain { } : AngouriMath.Core.Domain +AngouriMath.Entity+ProductOverSetf.Deconstruct(AngouriMath.Entity&, AngouriMath.Entity&, AngouriMath.Entity&) : System.Void +AngouriMath.Entity+ProductOverSetf.EqualityContract { } : System.Type +AngouriMath.Entity+ProductOverSetf.Equals(AngouriMath.Entity+CalculusOperator) : System.Boolean +AngouriMath.Entity+ProductOverSetf.Equals(AngouriMath.Entity+ProductOverSetf) : System.Boolean +AngouriMath.Entity+ProductOverSetf.Equals(System.Object) : System.Boolean +AngouriMath.Entity+ProductOverSetf.GetHashCode() : System.Int32 +AngouriMath.Entity+ProductOverSetf.InitDirectChildren() : AngouriMath.Entity[] +AngouriMath.Entity+ProductOverSetf.InnerDifferentiate(AngouriMath.Entity+Variable) : AngouriMath.Entity +AngouriMath.Entity+ProductOverSetf.InnerSimplify(System.Boolean) : AngouriMath.Entity +AngouriMath.Entity+ProductOverSetf.Over { } : AngouriMath.Entity +AngouriMath.Entity+ProductOverSetf.PrintMembers(System.Text.StringBuilder) : System.Boolean +AngouriMath.Entity+ProductOverSetf.Replace(System.Func) : AngouriMath.Entity +AngouriMath.Entity+ProductOverSetf.Substitute(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity +AngouriMath.Entity+ProductOverSetf.ToString() : System.String +AngouriMath.Entity+ProductOverSetf.ctor(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity) +AngouriMath.Entity+ProductOverSetf.op_Equality(AngouriMath.Entity+ProductOverSetf, AngouriMath.Entity+ProductOverSetf) : System.Boolean +AngouriMath.Entity+ProductOverSetf.op_Inequality(AngouriMath.Entity+ProductOverSetf, AngouriMath.Entity+ProductOverSetf) : System.Boolean AngouriMath.Entity+Productf.$() : AngouriMath.Entity+Productf AngouriMath.Entity+Productf.Codomain { } : AngouriMath.Core.Domain AngouriMath.Entity+Productf.Deconstruct(AngouriMath.Entity&, AngouriMath.Entity&, AngouriMath.Entity&, AngouriMath.Entity&) : System.Void @@ -3763,6 +3782,7 @@ AngouriMath.MathS.Piecewise(System.Collections.Generic.IEnumerable[]) : AngouriMath.Entity AngouriMath.MathS.Polygamma(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Pow(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity +AngouriMath.MathS.Product(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Product(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Provided(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Re(AngouriMath.Entity) : AngouriMath.Entity @@ -3962,6 +3982,7 @@ class AngouriMath.Entity+PrimeNuf class AngouriMath.Entity+PrimeOmegaf class AngouriMath.Entity+PrimePif class AngouriMath.Entity+Primef +class AngouriMath.Entity+ProductOverSetf class AngouriMath.Entity+Productf class AngouriMath.Entity+Providedf class AngouriMath.Entity+Quantifier diff --git a/Sources/Tests/UnitTests/Convenience/StringizeRoundTripTest.cs b/Sources/Tests/UnitTests/Convenience/StringizeRoundTripTest.cs index b46f8d169..70c6e1cd3 100644 --- a/Sources/Tests/UnitTests/Convenience/StringizeRoundTripTest.cs +++ b/Sources/Tests/UnitTests/Convenience/StringizeRoundTripTest.cs @@ -118,6 +118,9 @@ public void TheNodesWithoutAnOperatorSpellingPrintAsTheirFunction(string source) [InlineData("limitright(x, x, 0)")] [InlineData("dot(a, b)")] [InlineData("cross(a, b)")] + [InlineData("sum(x ^ 2, x in S)")] + [InlineData("product(x ^ 2, x in S)")] + [InlineData("product(1 - 1 / p ^ 2, p in { 2, 3, 5 })")] public void FunctionsRoundTrip(string source) => AssertRoundTrip(source); [Theory]