diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index a6acbfd03..2cad5a998 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -136,8 +136,12 @@ as `a - b = 0`, as a statement's own solve reads it: `"x + 1 = 3".Solve("x")` wa `Gamma(a, z) = int_z^oo t^(a - 1) e^(-t) dt`, as Mathematica's `Gamma[a, z]` is. - **Branch.** It takes the principal branch of `z^a`, with the cut on the negative real axis. - **Evaluation.** It is evaluated to the working precision for any complex `a` and `z`. -- **Derivative.** In `z` it is `-z^(a - 1) e^(-z)`. +- **Derivative.** In `z` it is `-z^(a - 1) e^(-z)`. At a negative `z` that power takes the real root for an exact + `a` of small odd denominator, so there it is not the derivative of the value + ([#204](https://github.com/asc-community/AngouriMath/issues/204)). - **Exact forms.** A whole `a >= 1` and `a = 1/2` are elementary. +- **Integrals.** Of a linear `u`, beside a polynomial, or beside any power of `x` but `1/x` where `u` is a multiple + of `x`, by parts, in gamma functions of `u`. ([#2075](https://github.com/asc-community/AngouriMath/issues/2075)) | Input | Was (2.6.0) | Now | @@ -145,6 +149,8 @@ as `a - b = 0`, as a statement's own solve reads it: `"x + 1 = 3".Solve("x")` wa | `"gamma(1/3, x)".ToEntity()` | a `FunctionArgumentCountException` | `gamma(1/3, x)` | | `"gamma(1/3, 2)".EvalNumerical()` | a `FunctionArgumentCountException` | `0.068136414441459136…` | | `"gamma(3, x)".ToEntity().InnerSimplified` | a `FunctionArgumentCountException` | `2 * e ^ (-x) * (1 + x + x ^ 2 / 2)` | +| `"x^2*gamma(0, a*x)".ToEntity().Integrate("x")` | a `FunctionArgumentCountException` | `x ^ 3 / 3 * gamma(0, a * x) - 1 / (3 * a ^ 3) * 2 * e ^ (-a * x) * (1 + a * x + (a * x) ^ 2 / 2) + C` | +| `"x^m*gamma(n, b*x)".ToEntity().Integrate("x")` | a `FunctionArgumentCountException` | `(x ^ (m + 1) * gamma(n, b * x) - x ^ m * (b * x) ^ (-m) * gamma(n + m + 1, b * x) / b) / (m + 1) + C` | ### Numerical equality is to half the evaluation's digits diff --git a/Sources/AngouriMath/Convenience/MathS.cs b/Sources/AngouriMath/Convenience/MathS.cs index 5e937153c..c588e75ea 100644 --- a/Sources/AngouriMath/Convenience/MathS.cs +++ b/Sources/AngouriMath/Convenience/MathS.cs @@ -1480,7 +1480,10 @@ public static Entity VectorLength(Matrix v) /// The node /// /// z^a takes its principal branch, so the cut is the negative real axis, which keeps the value from above. - /// Gamma(a, 0) is Gamma(a), and the derivative in z is -z^(a - 1) e^(-z). It is written + /// Gamma(a, 0) is Gamma(a), and the derivative in z is -z^(a - 1) e^(-z). At a negative + /// z the power there takes the real root for an exact a of small odd denominator, not the principal + /// branch, so for such an a it is not the derivative of the value + /// (https://github.com/asc-community/AngouriMath/issues/204). It is written /// gamma(a, z), as Mathematica's Gamma[a, z] and mpmath's gammainc(a, z) are. /// https://github.com/asc-community/AngouriMath/issues/2075 /// diff --git a/Sources/AngouriMath/Functions/Continuous/Integration/IntegralPatterns.cs b/Sources/AngouriMath/Functions/Continuous/Integration/IntegralPatterns.cs index 4d845c94b..bf99e98a6 100644 --- a/Sources/AngouriMath/Functions/Continuous/Integration/IntegralPatterns.cs +++ b/Sources/AngouriMath/Functions/Continuous/Integration/IntegralPatterns.cs @@ -68,6 +68,7 @@ internal static Entity AntiderivativeLog(Entity arg) Entity.Shif(var arg) => arg, Entity.Chif(var arg) => arg, Entity.Polygammaf(var order, var arg) when !order.ContainsNode(x) => arg, + Entity.IncompleteGammaf(var order, var arg) when !order.ContainsNode(x) => arg, Entity.Arcsinf(var arg) => arg, Entity.Arccosf(var arg) => arg, Entity.Arctanf(var arg) => arg, @@ -268,6 +269,188 @@ private static bool TakeMomentFactor(Entity factor, bool inverted, Entity.Variab _ => MathS.Pow(x, k + 1) * bell / (k + 1) + (-2 * A / (k + 1)).InnerSimplified * Moment(k + 2, A, bell, x), }; + /// + /// int P Gamma(n, u) dx for the upper incomplete gamma function of a linear + /// u = a + b x with n free of x, where P is a polynomial in + /// x, or, without an offset a, a power (d x)^m for any m but -1. + /// By parts against an antiderivative Q of P: the derivative of + /// Gamma(n, u) is -b u^(n - 1) e^(-u), and with Q written in powers of + /// u, each u^k lands on u^(n + k - 1) e^(-u), the derivative in u + /// of -Gamma(n + k, u). Rubi's 8.6. + /// https://github.com/asc-community/AngouriMath/issues/2075 + /// + private static Entity? IncompleteGammaBesideAPower(Entity expr, Entity.Variable x) + { + // Asked of every integrand that reaches the table, so a type test comes first, and + // nothing here captures a local. + if (expr is not (Entity.Mulf or Entity.Divf or Entity.IncompleteGammaf)) + return null; + var (numerator, denominator) = expr is Entity.Divf(var n, var d) ? (n, d) : (expr, (Entity)Entity.Number.Integer.One); + Entity coefficient = Entity.Number.Integer.One; + Entity.IncompleteGammaf? gamma = null; + Entity? above = null; + Entity? below = null; + foreach (var factor in Entity.Mulf.LinearChildren(numerator)) + if (!factor.ContainsNode(x)) + coefficient *= factor; + else if (gamma is null && factor is Entity.IncompleteGammaf incompleteGamma) + gamma = incompleteGamma; + else + above = above is null ? factor : above * factor; + foreach (var factor in Entity.Mulf.LinearChildren(denominator)) + if (!factor.ContainsNode(x)) + coefficient /= factor; + else if (below is null) + below = factor; + else + return null; + if (gamma is null || gamma.Parameter.ContainsNode(x) + || !TreeAnalyzer.TryGetPolyLinear(gamma.LowerLimit, x, out var slope, out var offset)) + return null; + var withoutAnOffset = TreeAnalyzer.IsZero(offset); + if (below is null && ThePowersOf(above, x, withoutAnOffset ? 100 : 32) is { } inX) + return (withoutAnOffset + ? BesideAPolynomialWithoutAnOffset(inX, gamma, slope, x) + : BesideAPolynomial(above ?? Entity.Number.Integer.One, gamma, slope, offset, x)) is { } answer + ? coefficient * answer + : null; + if (!withoutAnOffset) + return null; + + // A power of a multiple of x, of any exponent but -1, whose integral is not a gamma + // function: x^m Gamma(n, b x) is x^(m + 1) Gamma(n, b x)/(m + 1) - x^m (b x)^(-m) + // Gamma(m + n + 1, b x)/(b (m + 1)), and the quotient x^m/(b x)^m is b^(-m) for a whole m + // only: elsewhere the two powers take their branches separately, and it is constant only + // between the cuts. + Entity written; + Entity @base; + Entity scale; + Entity m; + if (below is null && above is not null && TryReadAPowerOfAMultiple(above, x, out @base, out scale, out m)) + written = above; + else if (above is null && below is not null && TryReadAPowerOfAMultiple(below, x, out @base, out scale, out var mBelow)) + { + written = 1 / below; + m = (-mBelow).InnerSimplified; + } + else + return null; + var mPlusOne = (m + 1).InnerSimplified; + if (TreeAnalyzer.IsZero(mPlusOne)) + return null; + // (d x)^(m + 1)/d, which is (d x)^m x on every branch. + var integrated = @base == x ? MathS.Pow(x, mPlusOne) : MathS.Pow(@base, mPlusOne) / scale; + var shifted = MathS.IncompleteGamma((gamma.Parameter + mPlusOne).InnerSimplified, gamma.LowerLimit); + var quotient = m is Entity.Number.Integer + ? MathS.Pow((scale / slope).InnerSimplified, m) + : written * MathS.Pow(gamma.LowerLimit, -m); + return coefficient * (integrated * gamma - quotient * shifted / slope) / mPlusOne; + } + + /// + /// 's coefficients by power of , with + /// read as 1, or where it is not a polynomial + /// of a degree from 0 to . + /// + private static Dictionary? ThePowersOf(Entity? polynomial, Entity.Variable x, int highest) + { + if (polynomial is null) + return new Dictionary { [EInteger.Zero] = Entity.Number.Integer.One }; + if (!TreeAnalyzer.TryGetPolynomial(polynomial, x, out var powers)) + return null; + foreach (var power in powers.Keys) + if (power.Sign < 0 || power.CompareTo(EInteger.FromInt32(highest)) > 0) + return null; + return powers; + } + + /// + /// int P(x) Gamma(n, b x) dx for P read into : each + /// c x^j is c (x^(j + 1) Gamma(n, b x) - Gamma(n + j + 1, b x)/b^(j + 1))/(j + 1). + /// + private static Entity BesideAPolynomialWithoutAnOffset(Dictionary powers, Entity.IncompleteGammaf gamma, Entity slope, Entity.Variable x) + { + Entity antiderivative = Entity.Number.Integer.Zero; + Entity shifted = Entity.Number.Integer.Zero; + foreach (var monomial in powers) + { + var next = Entity.Number.Integer.Create(monomial.Key.Add(1)); + antiderivative += monomial.Value * Power(x, next.EInteger.ToInt32Checked()) / next; + shifted += (monomial.Value / (next * Power(slope, next.EInteger.ToInt32Checked()))).InnerSimplified + * MathS.IncompleteGamma((gamma.Parameter + next).InnerSimplified, gamma.LowerLimit); + } + return antiderivative.InnerSimplified * gamma - shifted; + } + + /// + /// int P(x) Gamma(n, u) dx for u = a + b x with an offset: with P written + /// in powers of u, each p u^k is p (u^(k + 1) Gamma(n, u) - Gamma(n + k + 1, u))/(b (k + 1)). + /// + private static Entity? BesideAPolynomial(Entity polynomial, Entity.IncompleteGammaf gamma, Entity slope, Entity offset, Entity.Variable x) + { + // A power (c + d x)^k of a linear, the shape the integrand is usually written in, as + // the binomial it is in u: with s = b c - a d, c + d x is (s + d u)/b, so the weight of + // u^j is C(k, j) s^(k - j) d^j/((j + 1) b^(k + 1)), and the antiderivative vanishing at + // u = 0 is ((c + d x)^(k + 1) - (s/b)^(k + 1))/((k + 1) d). + var (linear, power) = polynomial is Entity.Powf(var written, Entity.Number.Integer exponent) ? (written, exponent.EInteger) : (polynomial, EInteger.One); + if (power.Sign > 0 && power.CompareTo(EInteger.FromInt32(32)) <= 0 && linear.ContainsNode(x) + && TreeAnalyzer.TryGetPolyLinear(linear, x, out var d, out var c)) + { + var k = power.ToInt32Checked(); + var s = (slope * c - offset * d).InnerSimplified; + var kPlusOne = Entity.Number.Integer.Create(k + 1); + Entity weighted = Entity.Number.Integer.Zero; + // Without a zeroth power, which is 1 provided its base is not 0. + for (var j = 0; j <= k; j++) + weighted += (Entity.Number.Rational.Create(Binomial(k, j).EInteger, EInteger.FromInt32(j + 1)) * Power(s, k - j) * Power(d, j)).InnerSimplified + * MathS.IncompleteGamma((gamma.Parameter + (j + 1)).InnerSimplified, gamma.LowerLimit); + return (MathS.Pow(linear, kPlusOne) / d - (MathS.Pow(s, kPlusOne) / (d * MathS.Pow(slope, kPlusOne))).InnerSimplified) / kPlusOne * gamma + - weighted / MathS.Pow(slope, kPlusOne); + } + var u = Entity.Variable.CreateUnique(polynomial + gamma + x, "u"); + if (ThePowersOf(polynomial.Substitute(x, (u - offset) / slope), u, 32) is not { } inU) + return null; + Entity antiderivative = Entity.Number.Integer.Zero; + Entity shifted = Entity.Number.Integer.Zero; + foreach (var monomial in inU) + { + var next = Entity.Number.Integer.Create(monomial.Key.Add(1)); + var weight = (monomial.Value / (next * slope)).InnerSimplified; + antiderivative += weight * Power(gamma.LowerLimit, next.EInteger.ToInt32Checked()); + shifted += weight * MathS.IncompleteGamma((gamma.Parameter + next).InnerSimplified, gamma.LowerLimit); + } + return antiderivative * gamma - shifted; + } + + private static Entity Power(Entity @base, int power) => power switch + { + 0 => Entity.Number.Integer.One, + 1 => @base, + _ => MathS.Pow(@base, power) + }; + + /// + /// read as (d x)^m, with d and m free of + /// : x itself, a power of it, or a power of a multiple of it. + /// + private static bool TryReadAPowerOfAMultiple(Entity factor, Entity.Variable x, out Entity @base, out Entity scale, out Entity exponent) + { + @base = x; + scale = exponent = Entity.Number.Integer.One; + if (factor == x) + return true; + if (factor is not Entity.Powf(var written, var power) || power.ContainsNode(x)) + return false; + exponent = power; + if (written == x) + return true; + if (!TreeAnalyzer.TryGetPolyLinear(written, x, out var multiple, out var offset) || !TreeAnalyzer.IsZero(offset)) + return false; + @base = written; + scale = multiple; + return true; + } + internal static Entity? TryStandardIntegrals(Entity expr, Entity.Variable x) => expr switch { // Every rule below divides by the linear rate of its integrand's argument, and @@ -397,6 +580,10 @@ _ when GaussianMoment(expr, x) is { } moment => moment, TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) => MathS.Ln(MathS.Factorial(arg - 1)) / a, + // The upper incomplete gamma function of a linear, alone or beside a power of x or a + // polynomial. https://github.com/asc-community/AngouriMath/issues/2075 + _ when IncompleteGammaBesideAPower(expr, x) is { } gamma => gamma, + Entity.Absf(var arg) when TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) => // ∫ |ax + b| dx = sgn(ax + b) * (ax + b)^2 / (2a) MathS.Signum(arg) * MathS.Pow(arg, 2) / (2 * a), diff --git a/Sources/Tests/UnitTests/Calculus/IncompleteGammaIntegrationTest.cs b/Sources/Tests/UnitTests/Calculus/IncompleteGammaIntegrationTest.cs new file mode 100644 index 000000000..b6571bf55 --- /dev/null +++ b/Sources/Tests/UnitTests/Calculus/IncompleteGammaIntegrationTest.cs @@ -0,0 +1,107 @@ +// +// 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.Linq; +using AngouriMath.Extensions; +using Xunit; + +namespace AngouriMath.Tests.Calculus +{ + /// + /// The upper incomplete gamma function of a linear, beside a power of x or a polynomial, by parts: the + /// remainder Q u^(n - 1) e^(-u) is a sum of derivatives of Gamma(n + k, u). Rubi's 8.6. + /// #2075 + /// + [Trait("Area", "Calculus")] + public sealed class IncompleteGammaIntegrationTest + { + private static Entity DifferentiatesBack(string integrand, double[] points) + { + var integral = integrand.ToEntity().Integrate("x"); + Assert.DoesNotContain("integral(", integral.Stringize()); + Entity Pinned(Entity e) => Pins.Aggregate(e, (current, pin) => current.Substitute(pin.Name, pin.Value.ToEntity())); + var derivative = Pinned(integral.Substitute("C", 0)).Differentiate("x"); + var original = Pinned(integrand.ToEntity()); + foreach (var at in points) + { + var got = derivative.Substitute("x", at).EvalNumerical(); + var want = original.Substitute("x", at).EvalNumerical(); + var difference = Math.Abs((double)(got - want).RealPart) + Math.Abs((double)(got - want).ImaginaryPart); + var scale = Math.Max(1.0, Math.Abs((double)want.RealPart) + Math.Abs((double)want.ImaginaryPart)); + Assert.True(difference / scale < 1e-9, $"d/dx of {integral} is {got} at x = {at}, where {integrand} is {want}"); + } + return integral; + } + + /// Where every integrand here is real. + private static readonly double[] Positive = { 0.35, 0.9, 1.45, 2.3 }; + + /// + /// And on the cut, at x = -1.7, for a whole order beside a whole power, where no power in the answer + /// takes the real root that an exact exponent of odd denominator takes on a negative base, against the + /// principal branch the function takes. + /// + private static readonly double[] AcrossTheCut = { -1.7, 0.35, 0.9, 1.45 }; + + private static readonly (string Name, string Value)[] Pins = + { ("a", "1/3"), ("b", "2/3"), ("c", "5/4"), ("d", "1/2"), ("m", "3/7"), ("n", "2/5") }; + + /// + /// Without an offset, beside (d x)^m for any m but -1: x^(m + 1) Gamma(n, b x)/(m + 1) + /// less x^m (b x)^(-m) Gamma(m + n + 1, b x)/(b (m + 1)), where x^m (b x)^(-m) is b^(-m) + /// for a whole m only. + /// + [Theory] + [InlineData("gamma(n, 2*x)/x^4")] + [InlineData("x^m*gamma(n, b*x)")] + [InlineData("(d*x)^m*gamma(n, b*x)")] + [InlineData("x^(3/2)*gamma(1/3, 2*x)")] + [InlineData("sqrt(x)*gamma(n, a*x)")] + public void BesideAPowerOfAMultipleOfX(string integrand) => DifferentiatesBack(integrand, Positive); + + [Theory] + [InlineData("gamma(0, a*x)")] + [InlineData("x^2*gamma(0, a*x)")] + [InlineData("x*gamma(-1, a*x)")] + [InlineData("gamma(0, a*x)/x^2")] + [InlineData("gamma(-2, a*x)/x^3")] + [InlineData("(c + d*x)*gamma(-1, a + b*x)")] + public void AWholeOrderBesideAWholePowerAcrossTheCut(string integrand) => DifferentiatesBack(integrand, AcrossTheCut); + + /// + /// With an offset, beside a polynomial written in powers of u = a + b x: Rubi's + /// (c + d x)^m Gamma(n, a + b x), in its b c - a d. + /// + [Theory] + [InlineData("gamma(n, a + b*x)")] + [InlineData("gamma(0, a + b*x)")] + [InlineData("(c + d*x)^2*gamma(n, a + b*x)")] + [InlineData("(c + d*x)*gamma(-1, a + b*x)")] + [InlineData("x^2*gamma(n, a + b*x)")] + [InlineData("x*(x + 1)*gamma(n, a + b*x)")] + public void BesideAPolynomialWithAnOffset(string integrand) => DifferentiatesBack(integrand, Positive); + + /// + /// As the function it is, rather than expanded: Gamma(100, a x) is a polynomial of degree 99 times + /// e^(-a x), and a hundred rounds of parts. + /// + [Fact] + public void AHighPowerIsAnsweredInClosedForm() + => Assert.Contains("gamma(100, a * x)", DifferentiatesBack("x^100*gamma(-1, a*x)", Positive).Stringize()); + + /// + /// Not beside 1/x, whose integral is a hypergeometric function, nor beside a power of a different + /// linear, which Rubi leaves unintegrated too. + /// + [Theory] + [InlineData("gamma(n, a*x)/x")] + [InlineData("gamma(n, a + b*x)/(c + d*x)")] + public void IsDeclinedWhereItIsNotAGammaFunction(string integrand) + => Assert.Contains("integral(", integrand.ToEntity().Integrate("x").Stringize()); + } +}