diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index d4ef9ba6c..35711e9ea 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -389,6 +389,29 @@ one form across the zeros. | `"sqrt(a + a*sin(x))".Integrate("x")` | unevaluated (`a^2 = a^2` is not decided by evaluation) | `-2 sqrt(2a) sgn(sin(u)) cos(u)` | | `"sqrt(1 + sin(x))".Integrate("x")` | `-2 cos(x)/sqrt(1 + sin(x))` | unchanged, the closed rule's | +### A partial-fraction coefficient with symbols in it is in lowest terms, its rational content included + +**Improvement, not silent.** The decomposition over written factors with symbols among their +coefficients put each coefficient in lowest terms by the polynomial gcd, which normalizes its +divisor to whole coprime coefficients and so never cancels a number: `-1024/(1024 a)` stayed as +it was. Newton's iteration for the inverse modulo a power of a quadratic squares its iterate every +round, so `tanh(x)^6/(a + a sech(x))` — `1/(u (1 + u^2)^6 (a (1 + u^2) + 2 a u))` under +`u = e^x` — had integers of twelve hundred digits by the third round and spent its minute in +their gcd. The rational content of the denominator now goes up into the numerator, and the values +the elimination solves for are put in lowest terms before the terms are built, where +`csch(x)^5/(a + b cosh(x))` after its Hermite reduction had two thousand nodes of `a` and `b` in +every term and each went round the chain without returning. And a constant factor in front of a +rational denominator is not a symbolic coefficient: `a (1 + u^2) + 2 a u` with its content out is +`a` times `(1 + u)^2`, which the refactoring over the rationals reads, and the answer is a page +shorter than the symbolic split's. + +| | Was | Is | +|---|---|---| +| `"tanh(x)^6/(a + a*sech(x))".Integrate("x")` | unevaluated after two minutes | `(-1/6 - 25/1536 e^x - … + 3/512 e^(10x))/(a (e^(2x) + 1)^5 (e^x + 1)) + ln(e^x)/a - …`, 2 s | +| `"csch(x)^5/(a + b*cosh(x))".Integrate("x")` | unevaluated | a piecewise on the sign of `a^2 - b^2`, its rational part `(1/4 (3a^3 - 7ab^2) e^x + 2b^3 e^(2x) + …)/(a^4 - 2a^2 b^2 + b^4)` over the factors, 1.3 s | +| `"1/(u*(u^2 + 1)^6*(a*(u^2 + 1) + 2*a*u))".Integrate("u")` | unevaluated | `(17/24 - 829/1536 u + … - 273/512 u^10)/(a (u^2 + 1)^5 (u + 1)) + ln(u)/a - 7/64 ln(u + 1)/a - 57/128 ln(u^2 + 1)/a - 329/512 arctan(u)/a` | +| `"u^5/((u^2 - 1)^5*(2*a*u + b*(u^2 + 1)))".Integrate("u")` | unevaluated | the same piecewise in `u`, its coefficients `1/256 (3a^3 - 7ab^2)/(a^4 - 2a^2 b^2 + b^4)` and the like rather than two thousand nodes each | + ### A condition the answer states on its own is no longer repeated beside it **Improvement, not silent.** `Simplify` returned `(1 - ln(x))/x^2 provided not x = 0` for the diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs index d3eb9e59e..8cf878242 100644 --- a/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs +++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs @@ -421,8 +421,16 @@ private static bool TryDivideMonomials(ulong dividend, ulong divisor, int variab /// that reads the way the answer is usually written: x + y, not /// -x/2 - y/2. /// - internal MultivariatePolynomial Normalized() + internal MultivariatePolynomial Normalized() => Normalized(out _); + + /// + /// , with the factor it was scaled by: the normalized + /// polynomial is this one times , and this one is the + /// normalized one over it. + /// + internal MultivariatePolynomial Normalized(out ERational scale) { + scale = ERational.One; if (IsZero) return this; var denominators = EInteger.One; @@ -434,7 +442,7 @@ internal MultivariatePolynomial Normalized() term.Value.Numerator.Multiply(denominators.Divide(term.Value.Denominator))); if (numerators.IsZero) return this; - var scale = ERational.Create(denominators, numerators); + scale = ERational.Create(denominators, numerators); if (terms[LeadingMonomial()].Sign < 0) scale = scale.Negate(); return ScaleBy(scale); diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/PartialFractions.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/PartialFractions.cs index 10fc7b987..ea8c1732e 100644 --- a/Sources/AngouriMath/Functions/Algebra/Polynomials/PartialFractions.cs +++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/PartialFractions.cs @@ -368,6 +368,13 @@ internal static bool TrySplitBiquadraticOverTheReals( private static Entity AsFraction(RationalPolynomial numerator, RationalPolynomial denominator, Variable x) => numerator.IsZero ? Integer.Create(0) : numerator.ToEntity(x) / denominator.ToEntity(x); + /// + /// The largest value of the elimination, by , that is + /// put in lowest terms over the symbols; the ones that needed it were two thousand + /// nodes, and the ones that could not be were twenty thousand. + /// + private const int LargestValuePutInLowestTerms = 4096; + /// /// N/D written as one fraction per factor of , /// where the denominator is written as a product of distinct linear and quadratic @@ -562,6 +569,21 @@ internal static bool TrySplitOverWrittenFactors( if (!TrySolveSquare(matrix, rhs, out var values)) return false; + // Each value in lowest terms over the symbols where there are any: the + // elimination hands back quotients of determinants, and `csch(x)^5/(a + b cosh(x))` + // under `u = e^x`, after the Hermite reduction, is a numerator with a page of + // `a` and `b` in it over `(u^2 - 1)(b + 2 a u + b u^2)`, whose values came out at + // two thousand nodes each, and the integrand each makes with its factor went round + // the chain and did not return. + // https://github.com/asc-community/AngouriMath/issues/718 + // Bounded: the lowest terms are an expansion and a gcd, and a value of twenty + // thousand nodes -- `cosh(c + d x)^6/(a + b sinh(c + d x)^2)^2` has four of them, + // and is answered in six seconds with them as they come -- did not return from + // either in three; past the bound a value is left as the elimination gave it. + if (values.Any(value => value.Vars.Any())) + for (var column = 0; column < width; column++) + if (values[column].Complexity <= LargestValuePutInLowestTerms) + values[column] = InLowestTermsOverTheSymbols(values[column]); Entity sum = 0; for (var i = 0; i < factors.Count; i++) { @@ -600,14 +622,51 @@ internal static Entity InLowestTermsOverTheSymbols(Entity constant) // order and eleven hundred nodes, and left uncancelled it carried into every // term of the answer. if (PolynomialGcd.TryCancel(expandedAbove, expandedBelow, out var cancelled, maxComplexity: 4096)) - return Bare(cancelled); + return WithThePrimitiveDenominator(Bare(cancelled)); // The gcd declines past its degree and step bounds, and a denominator that comes // out of a series is a product of written factors -- `b^9 (a^2 + b^2)^7` -- so the // common factor is one of them to some power: each is divided out of the // numerator exactly for as long as that goes. if (CancelledByTheWrittenFactors(expandedAbove, below) is { } byFactors) - return byFactors; - return expandedBelow == Integer.One ? expandedAbove : expandedAbove / expandedBelow; + return WithThePrimitiveDenominator(byFactors); + return WithThePrimitiveDenominator(expandedBelow == Integer.One ? expandedAbove : expandedAbove / expandedBelow); + } + + /// + /// with the rational content of its denominator moved + /// up: the denominator's coefficients whole and coprime with a positive leading one, + /// and the numerator scaled by what that took out. -1024/(1024 a) is + /// -1/a. + /// + /// + /// The polynomial gcd normalizes its divisor to whole coprime coefficients, so it + /// never cancels a number, and two sides without a variable in common are coprime to + /// it before it looks. Newton's iteration for the inverse modulo a power of a + /// quadratic squares its iterate every round, and an uncancelled 1024/1024 + /// after the first round was integers of twelve hundred digits after the third and + /// a minute of gcd on them for tanh(x)^6/(a + a sech(x)), which is a sum of + /// small fractions. + /// https://github.com/asc-community/AngouriMath/issues/718 + /// + private static Entity WithThePrimitiveDenominator(Entity quotient) + { + var (above, below) = SingleQuotient.Of(quotient); + if (below == Integer.One || below.Evaled is Complex { IsZero: true }) + return quotient; + var variables = above.Vars.Concat(below.Vars).Distinct().OrderBy(variable => variable.Name, System.StringComparer.Ordinal).ToArray(); + if (variables.Length > MultivariatePolynomial.MaxVariables) + return quotient; + var indices = new Dictionary(variables.Length); + for (var i = 0; i < variables.Length; i++) + indices[variables[i]] = i; + if (MultivariatePolynomial.TryParse(below, indices) is not { } bottom || bottom.IsZero + || MultivariatePolynomial.TryParse(above, indices) is not { } top) + return quotient; + var primitive = bottom.Normalized(out var scale); + if (scale.CompareTo(ERational.One) == 0) + return quotient; + var scaledTop = top.ScaleBy(scale).ToEntity(variables); + return primitive.IsConstant ? scaledTop : scaledTop / primitive.ToEntity(variables); } /// diff --git a/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs b/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs index e8bb3574c..a5be706b8 100644 --- a/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs @@ -594,6 +594,19 @@ is var (multiple, leftover) && (leftover is Divf(var leftoverTop, _) ? leftoverTop : leftover).InnerSimplified.Evaled is Number.Complex { IsZero: true }) return (multiple * MathS.Ln(denominator)).InnerSimplified; + // A written sum with a symbol among its coefficients that they all share is that + // symbol times a polynomial over the rationals, and is written so first: `(a u + a)` + // beside `1 - u^2` shares a root with it, which the symbolic split declines, and a + // symbolic sextic is nothing the refactoring below reads, where `a` times a rational + // one is. Before the symbolic split: `a (1 + u^2) + 2 a u` is `a (1 + u)^2`, a + // repeated linear over the rationals, and read as a quadratic with `a` in it the + // split computed its digits modulo `(1 + u^2)^6` with `a` in every coefficient, for + // an answer twice the length. Once: a primitive factor has no content to take out. + if (WithTheContentOutOfEachSumFactor(denominator, x) is { } primitive + && (SolveByPartialFractions(numerator / primitive, x, integrateByParts) + ?? Integration.ComputeIndefiniteIntegral(numerator / primitive, x, integrateByParts)) is { } overPrimitives) + return overPrimitives; + // Written linear factors with symbols in their coefficients, two or more, one of // them to a power: decomposed over the written factors, the coefficients read // off derivatives at the roots and each a line. First, before the respellings @@ -621,16 +634,6 @@ is var (multiple, leftover) // under a second this way, with the chain behind it for a spelling this rule does // not answer on its own -- one irreducible factor to the first power is the table's. // Once: the spelling this produces refactors to itself. - // A written sum with a symbol among its coefficients that they all share is that - // symbol times a polynomial over the rationals, and is written so first: `(a u + a)` - // beside `1 - u^2` shares a root with it, which the symbolic split declines, and a - // symbolic sextic is nothing the refactoring below reads, where `a` times a rational - // one is. Once: a primitive factor has no content to take out. - if (WithTheContentOutOfEachSumFactor(denominator, x) is { } primitive - && (SolveByPartialFractions(numerator / primitive, x, integrateByParts) - ?? Integration.ComputeIndefiniteIntegral(numerator / primitive, x, integrateByParts)) is { } overPrimitives) - return overPrimitives; - if (TryWriteInIrreducibleFactors(denominator, x) is { } refactored && (SolveByPartialFractions(numerator / refactored, x, integrateByParts) ?? Integration.ComputeIndefiniteIntegral(numerator / refactored, x, integrateByParts)) is { } overIrreducibles) @@ -10531,8 +10534,14 @@ private static bool IsAProductOfSymbolicLinearFactors(Entity denominator, Entity { var linears = 0; var quadratics = 0; + var symbolic = false; foreach (var factor in Mulf.LinearChildren(denominator)) { + // A constant factor is not a coefficient: `a u (1 + u^2)^6 (1 + 2 u + u^2)`, + // which taking the content out of `a (1 + u^2) + 2 a u` leaves, is a rational + // denominator with `a` in front, and the refactoring over the rationals and + // the Hermite reduction read it -- `(1 + u)^2` among them -- where the split + // took it as symbolic and answered in twice the length. if (!factor.ContainsNode(x)) continue; var @base = factor is Powf(var b, Number.Integer { EInteger.Sign: > 0 }) ? b : factor; @@ -10545,8 +10554,9 @@ private static bool IsAProductOfSymbolicLinearFactors(Entity denominator, Entity quadratics++; else return false; + symbolic |= read.Values.Any(coefficient => coefficient.Vars.Any()); } - return linears >= 1 && linears + quadratics >= 2 && denominator.Vars.Any(v => v != x); + return linears >= 1 && linears + quadratics >= 2 && symbolic; } /// diff --git a/Sources/Tests/UnitTests/Calculus/SymbolicFactorsPartialFractionsTest.cs b/Sources/Tests/UnitTests/Calculus/SymbolicFactorsPartialFractionsTest.cs index 4ddb897fa..fed7dadbc 100644 --- a/Sources/Tests/UnitTests/Calculus/SymbolicFactorsPartialFractionsTest.cs +++ b/Sources/Tests/UnitTests/Calculus/SymbolicFactorsPartialFractionsTest.cs @@ -233,6 +233,39 @@ public void ARepeatedSymbolicQuadraticBesideALinear(string integrand, int atMost Assert.True(length < atMost, $"{length} characters of answer for {integrand}"); } + /// + /// A coefficient of the decomposition is in lowest terms over the symbols, its + /// rational content included. The polynomial gcd normalizes its divisor to whole + /// coprime coefficients, so -1024/(1024 a) stayed as it was, and Newton's + /// iteration for the inverse modulo (1 + u^2)^6, which squares its iterate every + /// round, had integers of twelve hundred digits by the third round and spent its + /// minute in their gcd: tanh(x)^6/(a + a sech(x)) went from 650 ms to a timeout. + /// And the values the elimination solves for, where symbols are among them, are put + /// in lowest terms before the terms are built: csch(x)^5/(a + b cosh(x)), after + /// the Hermite reduction under u = e^x, had two thousand nodes of a and + /// b in every term, and the terms went round the chain and did not return. + /// And a constant factor is not a symbolic coefficient: with the content of + /// a (1 + u^2) + 2 a u out, the denominator is a rational one with a in + /// front, whose (1 + u)^2 the refactoring over the rationals reads, and the + /// answer is a page shorter than the split's. + /// + [Theory] + [InlineData("1/(u*(u^2 + 1)^6*(a*(u^2 + 1) + 2*a*u))", 1000)] + [InlineData("u^5/((u^2 - 1)^5*(2*a*u + b*(u^2 + 1)))", 30000)] + [InlineData("tanh(u)^6/(a + a*sech(u))", 8000)] + [InlineData("csch(u)^5/(a + b*cosh(u))", 30000)] + public void TheCoefficientsAreInLowestTerms(string integrand, int atMost) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + var integral = integrand.ToEntity().Integrate("u"); + watch.Stop(); + Assert.True(watch.Elapsed < IntegrationDecline.Guard, $"{integrand} took {watch.Elapsed.TotalSeconds:F1} s"); + Assert.DoesNotContain("integral(", integral.Stringize()); + var length = integral.Stringize().Length; + Assert.True(length < atMost, $"{length} characters of answer for {integrand}"); + DifferentiatesBack(integrand, "u", ("a", 1.7), ("b", 2.3)); + } + /// /// Two linear factors with one root are one factor: (a + b x)(a + x b)^2 is /// how the rules that make a factor monic and gather its powers write it, and as