diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index bbf7f4a34..314939ddb 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -93,6 +93,22 @@ root near 23. | `"x^7 - 5x^6 + 1 = 0".Solve("x")` | six roots, none of them near 5 | seven roots | | `"x^4 - 3*x^(5/2) + 2 = 0".Solve("x")` | `{ 1, 4.8870…^(2/5) }` | four roots: `1`, `1.3734…^2`, and two off the real line | +### l'Hopital's rule leaves out what only makes the derivatives larger + +**Limits whose derivatives grew without bound under l'Hopital's rule are answered, where they did not +finish or were left unevaluated.** The rule differentiates the whole of each side, and the product rule +carries every factor beside the one it differentiates. Now a factor that tends to a finite number other +than 0 at an infinity is replaced by that number, as one continuous at a finite point already was, and a +polynomial written on both sides is divided out. The quotient of two logarithms does the same with the +four parts it is built from. + +| Input | Was (2.6.0) | Now | +|---|---|---| +| `"ln(tanh(x) + x) / ln((x - pi)^2)".ToEntity().Limit("x", "+oo")` | did not finish in 30 s | `1/2` | +| `"ln(tanh(x) + x) / ln(x - pi)".ToEntity().Limit("x", "+oo")` | did not finish in 30 s | `1` | +| `"ln(arctan(x) + x) / ln(x)".ToEntity().Limit("x", "+oo")` | unevaluated | `1` | +| `"tanh(x) * x / (x + tanh(x))".ToEntity().Limit("x", "-oo")` | did not finish in 30 s | `-1` | + ### A complex constant does not make the two sides of a limit differ **A two-sided limit with a complex constant in it is answered where each side is, where it was NaN.** Where the diff --git a/Sources/AngouriMath/Functions/Continuous/Limits/Solvers/Limit.Solvers.cs b/Sources/AngouriMath/Functions/Continuous/Limits/Solvers/Limit.Solvers.cs index 3112f69c4..0fa5b956c 100644 --- a/Sources/AngouriMath/Functions/Continuous/Limits/Solvers/Limit.Solvers.cs +++ b/Sources/AngouriMath/Functions/Continuous/Limits/Solvers/Limit.Solvers.cs @@ -353,8 +353,19 @@ private static bool LogarithmDiverges(Entity argumentLimit) // quotients, the limit of ln(x - 1) / ln(ln(x)) at 1 from the left took twelve // seconds over (1/(x - 1)) / ((1/x) / ln(x)), where x ln(x) / (x - 1) takes a // hundredth of one. It took 14 ms before #2275 sent it to this rule. - var ratio = (upperDerivative * lowerLogArgument / (upperLogArgument * lowerDerivative)).InnerSimplified; + // A part that settles at a finite number other than 0 is that number in the limit, + // and left in it is differentiated with the rest: the derivative of x + tanh(x), + // 1 + 1/cosh(x)^2 written through exponentials, tends to 2, and multiplied into + // the quotient ln(x + tanh(x)) / ln(x - pi) did not finish in a minute. + var ratio = (Settled(upperDerivative) * Settled(lowerLogArgument) + / (Settled(upperLogArgument) * Settled(lowerDerivative))).InnerSimplified; return LimitFunctional.ComputeLimit(ratio, x, Real.PositiveInfinity); + Entity Settled(Entity part) + => part.ContainsNode(x) + && LimitFunctional.ComputeLimit(part, x, Real.PositiveInfinity) is { } limit + && limit.Evaled is Real { IsFinite: true, IsNaN: false, IsZero: false } + ? limit + : part; } else diff --git a/Sources/AngouriMath/Functions/Continuous/Limits/Transformations.cs b/Sources/AngouriMath/Functions/Continuous/Limits/Transformations.cs index 5715fad41..dbd527133 100644 --- a/Sources/AngouriMath/Functions/Continuous/Limits/Transformations.cs +++ b/Sources/AngouriMath/Functions/Continuous/Limits/Transformations.cs @@ -1609,7 +1609,8 @@ bool DoesNotSettle(Entity argument) => argument.ContainsNode(x) /// /// The factors of that are continuous at a finite destination with a - /// finite non-zero value there, as that value, and the product of the rest. + /// finite non-zero value there, as that value, or that tend to a finite non-zero limit at an + /// infinite one, as that limit, and the product of the rest. /// /// /// l'Hopital's rule differentiates both parts of the quotient, and a factor that tends to a @@ -1619,10 +1620,16 @@ bool DoesNotSettle(Entity argument) => argument.ContainsNode(x) /// in a minute, where x * (1 + x^2) / tanh(x) takes a tenth of a second. Only a factor real /// for real x and with no step in it, so that its value at the point is its limit from /// either side. + /// + /// At an infinity there is no value to substitute, and the factor's limit stands in for it: + /// lim c(x) f(x) / g(x) is lim c(x) times lim f(x) / g(x) wherever the first is a finite + /// number other than 0. Left in, tanh(x) * x / (x + tanh(x)) at +oo did not finish in a + /// minute, and with it ln(x + tanh(x)) / ln(x), whose derivatives' quotient it is; taken + /// out, x / (x + tanh(x)) is 1. /// - private static (Entity Value, Entity Others) TakeOutContinuousFactors(Entity expr, Variable x, Entity dest) + private static (Entity Value, Entity Others) TakeOutContinuousFactors(Entity expr, Variable x, Entity dest, ApproachFrom side) { - if (expr is not Mulf || !dest.IsFinite) + if (expr is not Mulf) return (Integer.One, expr); Entity value = Integer.One, rest = Integer.One; var any = false; @@ -1631,7 +1638,7 @@ private static (Entity Value, Entity Others) TakeOutContinuousFactors(Entity exp if (factor.ContainsNode(x) && !factor.Nodes.Any(static node => node is Floorf or Ceilf or Roundf or Signumf or Piecewise) && TreeAnalyzer.IsRealValued(factor, x) - && factor.Substitute(x, dest) is var there + && (dest.IsFinite ? factor.Substitute(x, dest) : IsAPolynomialPower(factor, x) ? MathS.NaN : ComputeLimit(factor, x, dest, side) ?? MathS.NaN) is var there && there.Evaled is Real { IsFinite: true, IsNaN: false, IsZero: false }) { value *= there; @@ -1643,6 +1650,88 @@ private static (Entity Value, Entity Others) TakeOutContinuousFactors(Entity exp return any && rest.ContainsNode(x) ? (value.InnerSimplified, rest.InnerSimplified) : (Integer.One, expr); } + /// Whether is built from and real constants by sums, differences, products and positive whole powers. + private static bool IsAPolynomialIn(Entity node, Variable x) => node switch + { + _ when !node.ContainsNode(x) => node.Evaled is Real { IsFinite: true }, + Variable variable => variable == x, + Sumf(var left, var right) => IsAPolynomialIn(left, x) && IsAPolynomialIn(right, x), + Minusf(var left, var right) => IsAPolynomialIn(left, x) && IsAPolynomialIn(right, x), + Mulf(var left, var right) => IsAPolynomialIn(left, x) && IsAPolynomialIn(right, x), + Powf(var @base, Integer { EInteger.Sign: > 0 }) => IsAPolynomialIn(@base, x), + _ => false + }; + + /// + /// Whether is a polynomial in that is not a + /// constant, or one to a whole power, which at an infinity tends to an infinity or to 0 and + /// never to a finite number other than 0, so that asking its limit is wasted. + /// + private static bool IsAPolynomialPower(Entity factor, Variable x) + => factor.ContainsNode(x) && (factor is Powf(var @base, Integer) ? IsAPolynomialIn(@base, x) : IsAPolynomialIn(factor, x)); + + /// + /// over with every factor that + /// is a polynomial in , not identically 0, and written on both sides to + /// a whole power, divided out by the smaller of the two powers; null where there is none. + /// + /// + /// A polynomial that is not identically 0 has finitely many zeros, so it is not 0 anywhere + /// on a punctured neighbourhood of a point or of an infinity close enough in, and the two + /// quotients agree there. Differentiated instead, the factor is carried through the product + /// rule with everything beside it: (x - pi)^2 / ((x + tanh(x)) * (x - pi)) at +oo took + /// seven seconds, where x^2 / ((x + tanh(x)) * x), whose x the normalisation cancels, took + /// a fortieth of one; and ln(x + tanh(x)) / ln((x - pi)^2), which l'Hopital's rule turns + /// into the first, did not finish. + /// + private static Entity? WithThePolynomialFactorsOnBothSidesCancelled(Entity numerator, Entity denominator, Variable x) + { + var above = Powers(numerator); + var below = Powers(denominator); + var cancelledAny = false; + foreach (var @base in above.Keys.ToList()) + if (below.TryGetValue(@base, out var underneath) && IsAPolynomial(@base) && !VanishesIdentically(@base)) + { + var common = Math.Min(above[@base], underneath); + above[@base] -= common; + below[@base] -= common; + cancelledAny = true; + } + if (!cancelledAny) + return null; + // Only where what is left is still a quotient of two functions of x: 3x^2 / (x^3 * f(x)) + // at 0 became 3 / (x * f(x)), which is no longer a question for this rule, and the + // limits machinery took more than twenty seconds over it where differentiating took one. + var (top, bottom) = (Rebuild(above), Rebuild(below)); + return top.ContainsNode(x) && bottom.ContainsNode(x) ? top / bottom : null; + + static Dictionary Powers(Entity side) + { + var powers = new Dictionary(); + foreach (var factor in Mulf.LinearChildren(side)) + { + var (@base, power) = factor is Powf(var repeated, Integer { EInteger.Sign: > 0 } times) && times.EInteger.CanFitInInt32() + ? (repeated, times.EInteger.ToInt32Unchecked()) : (factor, 1); + powers[@base] = powers.TryGetValue(@base, out var already) ? already + power : power; + } + return powers; + } + static Entity Rebuild(Dictionary powers) + { + Entity built = Integer.One; + foreach (var pair in powers) + if (pair.Value > 0) + built *= pair.Value == 1 ? pair.Key : MathS.Pow(pair.Key, pair.Value); + return built.InnerSimplified; + } + bool IsAPolynomial(Entity node) => node.ContainsNode(x) && IsAPolynomialIn(node, x); + // At two points, since a polynomial that is not 0 everywhere may still be 0 at one: + // x - x is not cancelled, as 0 / 0 is not 1. + bool VanishesIdentically(Entity polynomial) + => polynomial.Substitute(x, Rational.Create(7, 3)).Evaled == Integer.Zero + && polynomial.Substitute(x, Rational.Create(-11, 5)).Evaled == Integer.Zero; + } + private static Entity? ApplylHopitalRuleImpl(Entity expr, Variable x, Entity dest, ApproachFrom side) { if (expr is not Divf && AsQuotient(expr, x, dest, side) is { } quotient) @@ -1655,9 +1744,13 @@ private static (Entity Value, Entity Others) TakeOutContinuousFactors(Entity exp if (num.ContainsNode(x) && den.ContainsNode(x) && !HasAStepThatJumpsNear(expr, x, dest, side)) { - var (numValue, numRest) = TakeOutContinuousFactors(num, x, dest); - var (denValue, denRest) = TakeOutContinuousFactors(den, x, dest); + var (numValue, numRest) = TakeOutContinuousFactors(num, x, dest, side); + var (denValue, denRest) = TakeOutContinuousFactors(den, x, dest, side); var taken = (numValue / denValue).InnerSimplified; + // A factor written on both sides is divided out rather than + // differentiated, and the smaller quotient is asked instead. + if (WithThePolynomialFactorsOnBothSidesCancelled(numRest, denRest, x) is { } cancelled) + return ComputeLimit(cancelled, x, dest, side) is { } cancelledLimit ? Times(taken, cancelledLimit) : null; // Simplified, because the shape of the quotient is what the // machinery below matches on and differentiation does not // produce it: d/dx ln(x)^2 is 2 * ln(x) * (1 / x), a product @@ -1686,7 +1779,13 @@ private static (Entity Value, Entity Others) TakeOutContinuousFactors(Entity exp // cos(x) * (e^x - e^(-x)), and its derivatives' quotient, which is 2 at 0, // was turned away, so cos(x) * sinh(x) / sin(x) from the right at 0 was // left unevaluated, and ln(sin(x)) / ln(sinh(x)) with it. - if (GrewTooMuch(expr, applied)) + // At an infinity the growth is measured against what was differentiated, not + // against the quotient with the settling factors still in it, which the + // taking out would otherwise count as room to grow: + // log(x, 1/2) ^ (e^x - sgn(x)) at 0 from the right, whose descent reaches + // here at +oo with e^(1/x) taken out, took nine seconds where it took a half. + // At a finite point the bound is as it was, whose taking out it was set for. + if (GrewTooMuch(dest.IsFinite ? expr : numRest / denRest, applied)) return ItsValueAt(applied, x, dest) is { } value ? Times(taken, value) : null; lHopitalApplications++; MultithreadingFunctional.ExitIfCancelled(); diff --git a/Sources/Tests/UnitTests/Calculus/LhopitalKeepsTheDerivativesSmallTest.cs b/Sources/Tests/UnitTests/Calculus/LhopitalKeepsTheDerivativesSmallTest.cs new file mode 100644 index 000000000..f509b1b68 --- /dev/null +++ b/Sources/Tests/UnitTests/Calculus/LhopitalKeepsTheDerivativesSmallTest.cs @@ -0,0 +1,47 @@ +// +// 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; +using System.Threading.Tasks; +using AngouriMath.Core; +using Xunit; + +namespace AngouriMath.Tests.Calculus +{ + /// + /// l'Hopital's rule differentiates the whole of each side, and the product rule carries every + /// factor beside the one it differentiates. A factor that settles at a number other than 0, or a + /// polynomial written on both sides, only makes the derivatives larger, and with tanh written + /// through exponentials they did not finish: ln(x + tanh(x)) / ln((x - pi)^2) at +oo, + /// which is 1/2, was still running after a minute. Found by limitcheck at DEPTH=3; no + /// issue was filed. + /// + [Trait("Area", "Calculus")] + public sealed class LhopitalKeepsTheDerivativesSmallTest + { + [Theory] + [InlineData("ln(tanh(x) + x) / ln((x - pi)^2)", "+oo", "1/2")] + [InlineData("ln(tanh(x) + x) / ln(x - pi)", "+oo", "1")] + [InlineData("ln(tanh(x) + x) / ln(x)", "+oo", "1")] + [InlineData("ln(arctan(x) + x) / ln(x)", "+oo", "1")] + [InlineData("tanh(x) * x / (x + tanh(x))", "-oo", "-1")] + [InlineData("(x - pi)^2 / ((x + tanh(x)) * (x - pi))", "+oo", "1")] + [InlineData("arctan(x) * x / (x + 1)", "+oo", "pi / 2")] + [InlineData("(x - 1)^2 * sin(x - 1) / ((x - 1)^3 * cos(x))", "1", "sec(1)")] + public void Finishes(string input, string destination, string expected) + { + var limit = Task.Run(() => MathS.FromString(input).Limit("x", destination).Simplify()); + Assert.True(limit.Wait(TimeSpan.FromSeconds(60)), $"{input} at {destination} did not finish"); + Assert.Equal(MathS.FromString(expected).Simplify(), limit.Result); + } + + // A factor that is 0 everywhere is not cancelled: 0 / 0 is not 1. + [Fact] + public void DoesNotCancelAFactorThatIsZeroEverywhere() + => Assert.Equal(MathS.NaN, MathS.FromString("(x - x) * sin(x) / ((x - x) * x)").Limit("x", 0)); + } +}