diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index ef5d61b33..d036a8063 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -589,6 +589,27 @@ arctangent it is ([#718](https://github.com/asc-community/AngouriMath/issues/718 | `"(A + B*x + C*x^2)*sqrt(c + d*x)/((a + b*x)^3*sqrt(e + f*x))".ToEntity().Integrate("x")` | `integral(...)` | the roots over powers of `a + b x`, a logarithm, and an arctangent | | `"x^2*sqrt(a + 2*x)*sqrt(c - 3*x)".ToEntity().Integrate("x")` | `integral(...)` | a cubic times the two roots, and an arctangent of `sqrt(6)/2 sqrt(a + 2 x)/sqrt(c - 3 x)` | +### A polynomial over a power of a linear beside the root of a quadratic is integrated + +`P(x) Q^(m/2)/(g + h x)^k`, a polynomial over a power of a linear beside a half-odd power of a +quadratic `Q`, was left unevaluated wherever the linear was below the bar to a power past the +first, and with a symbol in the linear or in `Q` even to the first. These are Rubi's 1.2.1.9, and +with a constant or linear `P`, 1.2.1.2 to 1.2.1.4. They are now integrated by undetermined +coefficients, as the roots of two linears are. The answer is a rational function times `sqrt(Q)`, +a logarithm or an arcsine by the sign of the leading coefficient of `Q`, and a logarithm or an +arctangent by the sign of `Q` at the linear's root. Where the linear shares a root with `Q`, there +is no third term. Below the root's first power, `m < -1`, and without the linear, the answers are +as they were ([#718](https://github.com/asc-community/AngouriMath/issues/718)). + +| Input | Was (2.5.0) | Now | +|---|---|---| +| `"1/((g + h*x)*sqrt(a + c*x^2))".ToEntity().Integrate("x")` | `integral(...)` | a logarithm in `(a h - c g x)/(sqrt(a h^2 + c g^2) sqrt(a + c x^2))` where `a h^2 + c g^2 > 0`, and an arctangent where it is negative | +| `"(d + k*x + f*x^2)*sqrt(a + c*x^2)/(g + h*x)^4".ToEntity().Integrate("x")` | `integral(...)` | powers of `1/(g + h x)` times `sqrt(a + c x^2)`, a logarithm or an arcsine, and the same as above | +| `"(2 + x + 3*x^2 - x^3 + 5*x^4)*sqrt(3 - x + 2*x^2)/(5 + 2*x)^5".ToEntity().Integrate("x")` | `integral(...)` | powers of `1/(5 + 2 x)` times the root, and two logarithms | +| `"(A + B*x + F*x^2)*sqrt(d^2 - m^2*x^2)/(d + m*x)^2".ToEntity().Integrate("x")` | `integral(...)` | a rational function times the root, and an arcsine | +| `"sqrt(1 - x^2)/(1 + x)^2".ToEntity().Integrate("x")` | `integral(...)` | `-2 sqrt(1 - x^2)/(1 + x) + arcsin(-x)` | +| `"sqrt(x^2 + 1)/x^2".ToEntity().Integrate("x")` | `integral(...)` | `-sqrt(x^2 + 1)/x + ln(2 sqrt(x^2 + 1) + 2 x)` | + ### A function comes out of a fractional power of its even power with its sign **Improvement, not silent.** The entry two above made `(sin(x)^2)^(3/2)` the modulus `|sin(x)|^3` diff --git a/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs b/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs index d9e12515a..261c1f821 100644 --- a/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs @@ -8395,37 +8395,20 @@ static Entity WithWholePowersOfTheSecond(List<(EInteger Power, Entity Coefficien /// Write S = sqrt(a + b x) sqrt(c + d x) and Q = (a + b x)(c + d x). Over /// S the integrand is T(x)/((g + h x)^k S), where /// T = P (a + b x)^((m + 1)/2) (c + d x)^((n + 1)/2) is a polynomial, and - /// S' = Q'/(2 S) because sqrt(z)^2 = z for every complex z. - /// - /// - /// The polynomial part. In powers of y = g + h x, the terms of T from - /// y^k up leave a polynomial R(x), and - /// int R/S = U S + lambda int 1/S. The derivative of U S is - /// (U' Q + U Q'/2)/S, so R = U' Q + U Q'/2 + lambda, which for U of one - /// degree less than R is triangular. With - /// Q = q0 + q1 x + q2 x^2, the coefficient of x^j on the right is - /// (j + 1) q0 u_(j+1) + (j + 1/2) q1 u_j + j q2 u_(j-1). That is solved for - /// u_(j-1) from the top down, and lambda is what is left at x^0. - /// - /// - /// The terms over powers of y. Write Q = alpha + beta y + gamma y^2. - /// The derivative of S y^(1-j) is - /// h (2 (1 - j) alpha y^(-j) + (3 - 2j) beta y^(1-j) + (4 - 2j) gamma y^(2-j)) / (2 S). - /// So for j >= 2, I_j = int 1/(y^j S) is given by S y^(1-j) and the two - /// integrals before it, and all the way down it is algebraic terms and a multiple of - /// I_1. That needs alpha, the value of Q at the root of y, to be - /// nonzero, so a third linear that shares a root with one under a root is declined. + /// takes that to algebraic terms and two + /// integrals, as it does for the root of one quadratic. /// /// /// The two integrals left. With t = sqrt(a + b x)/sqrt(c + d x), /// dx/S = 2 dt/(b - d t^2), so int 1/S is 2 artanh(sqrt(r) t)/(b sqrt(r)) - /// with r = d/b. And dx/(y S) = -2 dt/(p t^2 + q) with p = g d - h c - /// and q = h a - g b, so I_1 is -2 arctan(sqrt(rho) t)/(q sqrt(rho)) - /// with rho = p/q. Each derivative needs only sqrt(z)^2 = z, so each holds for every - /// value of the symbols that the divisions allow. Where r or rho is a number - /// of the other sign, the integral is written as the other function, without an i - /// in it. The slopes are divided by, which is the generic case, as everywhere in the - /// integrator. + /// with r = d/b. And dx/(y S) = -2 dt/(p t^2 + q) with y = g + h x, + /// p = g d - h c and q = h a - g b, so int 1/(y S) is + /// -2 arctan(sqrt(rho) t)/(q sqrt(rho)) with rho = p/q. Each derivative + /// needs only sqrt(z)^2 = z, so each holds for every value of the symbols that the + /// divisions allow. Each is real for one sign of r or rho and the other + /// function for the other sign: the one for the sign of a number, and both, each where + /// it holds, for a quantity with symbols in it. The slopes are divided by, which is the + /// generic case, as everywhere in the integrator. /// /// /// The substitution answers the same @@ -8465,17 +8448,188 @@ static Entity WithWholePowersOfTheSecond(List<(EInteger Power, Entity Coefficien || !first.Vars.Concat(second.Vars).Any(symbol => symbol != x) || !TreeAnalyzer.TryGetPolyLinear(first, x, out var b, out var a) || !TreeAnalyzer.TryGetPolyLinear(second, x, out var d, out var c) - || IsZero(b) || IsZero(d) || IsZero(b * c - a * d)) + || IsZeroOverTheSymbols(b) || IsZeroOverTheSymbols(d) || IsZeroOverTheSymbols(b * c - a * d)) + return null; + if (ReadBesideSquareRoots(expr, x, first, second) is not var (halves, above, constantBelow, third, order)) return null; + // (a + b x)^(m/2) is (a + b x)^((m + 1)/2) over its root. Below -1 there is a pole + // at the root of a linear under a root, which is the substitution's. + if (halves[first] % 2 == 0 || halves[second] % 2 == 0) + return null; + var wholeOfFirst = (halves[first] + 1) / 2; + var wholeOfSecond = (halves[second] + 1) / 2; + if (wholeOfFirst < 0 || wholeOfSecond < 0 + || CoefficientsBesideARoot(above * WholePower(first, wholeOfFirst) * WholePower(second, wholeOfSecond), x) is not { } t) + return null; + + // h^2 Q at the third linear's root is (h a - g b)(h c - g d), zero where it shares a + // root with one under a root. + ALinearBesideTheRoot? pole = null; + if (third is { }) + { + if (!TreeAnalyzer.TryGetPolyLinear(third, x, out var h, out var g) || IsZeroOverTheSymbols(h)) + return null; + pole = new(third, g, h, order, new[] { h * a - g * b, h * c - g * d }, SharesARoot: false); + } + if (IntegrateOverARootOfAQuadratic(expr, x, t, a * c, a * d + b * c, b * d, xi => (a + b * xi) * (c + d * xi), pole, b, 0) + is not var (algebraic, ofTheLogarithm, ofTheThirdKind)) + return null; + var answer = algebraic * MathS.Sqrt(first) * MathS.Sqrt(second); + var root = MathS.Sqrt(first) / MathS.Sqrt(second); + if (ofTheLogarithm != Number.Integer.Zero) + { + // int 1/S over 1/b, with 2 artanh(z) written as the logarithm the library writes it as. + var r = LowestOverTheSymbols(d / b); + answer = answer + BySign(r, + ofTheLogarithm * MathS.Ln((1 + MathS.Sqrt(r) * root) / (1 - MathS.Sqrt(r) * root)) / MathS.Sqrt(r), + 2 * ofTheLogarithm * MathS.Arctan(MathS.Sqrt(-r) * root) / MathS.Sqrt(-r)); + } + if (ofTheThirdKind != Number.Integer.Zero) + { + // int 1/(y S) over 1/(h a - g b), -2 arctan(sqrt(rho) t)/sqrt(rho) with + // rho = (g d - h c)/(h a - g b). + var atThePole = pole!.AtThePole; + var rho = LowestOverTheSymbols(-atThePole[1] / atThePole[0]); + answer = answer + BySign(rho, + -2 * ofTheThirdKind * MathS.Arctan(MathS.Sqrt(rho) * root) / MathS.Sqrt(rho), + -ofTheThirdKind * MathS.Ln((1 + MathS.Sqrt(-rho) * root) / (1 - MathS.Sqrt(-rho) * root)) / MathS.Sqrt(-rho)); + } + return (constantBelow == Number.Integer.One ? answer : answer / constantBelow).InnerSimplified; + } + + /// + /// A polynomial over a power of a linear beside a half-odd power of a quadratic, + /// P(x) Q^(m/2) / (g + h x)^k with m odd and not below -1, and + /// k >= 0, by undetermined coefficients: algebraic terms times sqrt(Q), and + /// a multiple of each of two integrals that are not algebraic. + /// + /// + /// + /// Over S = sqrt(Q) the integrand is T(x)/((g + h x)^k S), where + /// T = P Q^((m + 1)/2) is a polynomial, and + /// takes that to algebraic terms and two + /// integrals. + /// + /// + /// The two integrals left. With Q = q0 + q1 x + q2 x^2, int 1/S is + /// ln(2 sqrt(q2) S + 2 q2 x + q1)/sqrt(q2), and + /// -arcsin((2 q2 x + q1)/sqrt(q1^2 - 4 q0 q2))/sqrt(-q2), real where q2 < 0, + /// as the root of a quadratic alone is answered. With y = g + h x, + /// H = q0 h^2 - q1 g h + q2 g^2, which is h^2 Q at the root of y, and + /// Z = 2 q0 h - q1 g + (q1 h - 2 q2 g) x, int 1/(y S) is + /// -artanh(Z/(2 sqrt(H) S))/sqrt(H), written as the logarithm the library writes it + /// as, and arctan(Z/(2 sqrt(-H) S))/sqrt(-H), real where H < 0. The + /// derivative of each of those two needs only sqrt(z)^2 = z. Each pair is given by + /// the sign of its quantity, as for the roots of two linears. And since + /// Z^2 - 4 H Q is (q1^2 - 4 q0 q2) y^2, the artanh is of a number less than + /// 1 in size where Q has no real root, and of one more than 1 where it has two: + /// there it is written as the logarithm of (z + 1)/(z - 1), which differs from + /// that of (1 + z)/(1 - z) by a constant and is the real one. + /// + /// + /// Where it is asked. Only with the linear below the bar. A polynomial beside the + /// root alone is 's, which also + /// answers a leading coefficient that is zero. A first power of the linear with numbers in + /// it and in Q is 's, whose answer + /// is real on both sides of the linear's root, and + /// takes distinct linears + /// apart into it. A power past the first is this rule's, and so is a first power with a + /// symbol in it, which those decline: 1/((g + h x) sqrt(a + c x^2)) was declined. + /// + /// + /// Rubi's 1.2.1.9, (d + e x + f x^2) sqrt(a + c x^2)/(g + h x)^4 and its like, was + /// declined or ran past its budget, where this is a triangular system and a recurrence. + /// https://github.com/asc-community/AngouriMath/issues/718 + /// + /// + internal static Entity? SolveAPolynomialOverAPowerOfALinearBesideARootOfAQuadratic(Entity expr, Entity.Variable x) + { + // The quadratic, read before anything is built, since this asks every sub-integrand. + Entity? quadratic = null; + foreach (var node in expr.Nodes) + { + if (node is not Powf(var @base, Number.Rational exponent) || exponent is Number.Integer || !@base.ContainsNode(x)) + continue; + if (!exponent.ERational.Denominator.Equals(EInteger.FromInt32(2)) || !exponent.ERational.Numerator.CanFitInInt32() + || quadratic is { } && quadratic != @base) + return null; + quadratic = @base; + } + // A square below the root is the modulus of its root, which the rules for it take; and + // each closed form is chosen by the sign of a quantity, which a number off the real + // line does not have. Without the linear, and with a first power of it and numbers + // only, the rules further down answer: see the remarks. + if (quadratic is null || HoldsTheImaginaryUnit(expr) || CoefficientsBesideARoot(quadratic, x) is not { Length: 3 } q + || IsZeroOverTheSymbols(q[2]) || IsZeroOverTheSymbols(q[1] * q[1] - 4 * q[0] * q[2]) + || ReadBesideSquareRoots(expr, x, quadratic) is not var (halves, above, constantBelow, third, order) + || order == 0 || order == 1 && !quadratic.Vars.Concat(third!.Vars).Any(symbol => symbol != x)) + return null; + + // Q^(m/2) is Q^((m + 1)/2) over its root. + if (halves[quadratic] % 2 == 0 || halves[quadratic] < -1 + || CoefficientsBesideARoot(above * WholePower(quadratic, (halves[quadratic] + 1) / 2), x) is not { } t) + return null; + var (q0, q1, q2) = (q[0], q[1], q[2]); + ALinearBesideTheRoot? pole = null; + if (third is { }) + { + if (!TreeAnalyzer.TryGetPolyLinear(third, x, out var h, out var g) || IsZeroOverTheSymbols(h)) + return null; + // h^2 Q at the linear's root; where that is zero, h Q' there, which is not, since + // the root is a simple one. + var atTheRoot = q0 * h * h - q1 * g * h + q2 * g * g; + pole = IsZeroOverTheSymbols(atTheRoot) + ? new(third, g, h, order, new[] { q1 * h - 2 * q2 * g }, SharesARoot: true) + : new(third, g, h, order, new[] { atTheRoot }, SharesARoot: false); + } + if (IntegrateOverARootOfAQuadratic(expr, x, t, q0, q1, q2, xi => quadratic.Substitute(x, xi), pole, null, null) + is not var (algebraic, ofTheFirstKind, ofTheThirdKind)) + return null; + var root = MathS.Sqrt(quadratic); + var answer = algebraic * root; + if (ofTheFirstKind != Number.Integer.Zero) + { + var derivative = 2 * q2 * x + q1; + answer = answer + BySign(q2, + ofTheFirstKind * MathS.Ln(2 * MathS.Sqrt(q2) * root + derivative) / MathS.Sqrt(q2), + -ofTheFirstKind * MathS.Arcsin(LowestOverTheSymbols(derivative / MathS.Sqrt(q1 * q1 - 4 * q0 * q2))) / MathS.Sqrt(-q2)); + } + if (ofTheThirdKind != Number.Integer.Zero) + { + var (_, g, h, _, atThePole, _) = pole!; + var z = 2 * q0 * h - q1 * g + (q1 * h - 2 * q2 * g) * x; + var twiceTheRoot = 2 * MathS.Sqrt(atThePole[0]) * root; + // z^2 - 4 H Q is (q1^2 - 4 q0 q2) (g + h x)^2, so z/(2 sqrt(H) S) is less than 1 in + // size where that is negative, and the logarithm of (1 + it)/(1 - it) is real, and + // more where it is positive, and the logarithm of (it + 1)/(it - 1) is. + Entity Logarithm(Entity ratio) => -ofTheThirdKind * MathS.Ln(ratio) / (2 * MathS.Sqrt(atThePole[0])); + answer = answer + BySigns(atThePole[0], q1 * q1 - 4 * q0 * q2, + Logarithm((z + twiceTheRoot) / (z - twiceTheRoot)), + Logarithm((twiceTheRoot + z) / (twiceTheRoot - z)), + ofTheThirdKind * MathS.Arctan(z / (2 * MathS.Sqrt(-atThePole[0]) * root)) / MathS.Sqrt(-atThePole[0])); + } + return (constantBelow == Number.Integer.One ? answer : answer / constantBelow).InnerSimplified; + } + + /// + /// as one quotient beside the square roots of + /// : the power of each root counted in halves, above the bar + /// and below; the rest of what is above; the constants below; and one more factor with + /// x in it below, to a whole power, if there is one. Null where there is anything else + /// below. + /// + private static (Dictionary Halves, Entity Above, Entity ConstantBelow, Entity? Third, int Order)? + ReadBesideSquareRoots(Entity expr, Entity.Variable x, params Entity[] radicands) + { // As one quotient, with a negative half-power read as the root below the bar it is. - // Each root's power is counted in halves, above the bar and below; anything else of x - // above is the polynomial, and below it may be powers of one more linear. var (numerator, denominator) = Functions.SingleQuotient.Of(expr.Replace(node => node is Powf(var @base, Number.Rational power) && power is not Number.Integer && power.ERational.Sign < 0 ? Number.Integer.One / MathS.Pow(@base, Number.Rational.Create(power.ERational.Negate())) : node)); - var halves = new Dictionary { [first] = 0, [second] = 0 }; + var halves = new Dictionary(); + foreach (var radicand in radicands) + halves[radicand] = 0; Entity above = Number.Integer.One; Entity constantBelow = Number.Integer.One; Entity? third = null; @@ -8509,59 +8663,103 @@ node is Powf(var @base, Number.Rational power) && power is not Number.Integer && order += inHalves / 2; } } - // (a + b x)^(m/2) is (a + b x)^((m + 1)/2) over its root. Below -1 there is a pole - // at the root of a linear under a root, which is the substitution's. - if (halves[first] % 2 == 0 || halves[second] % 2 == 0) - return null; - var wholeOfFirst = (halves[first] + 1) / 2; - var wholeOfSecond = (halves[second] + 1) / 2; - if (wholeOfFirst < 0 || wholeOfSecond < 0) - return null; - above = above * Power(first, wholeOfFirst) * Power(second, wholeOfSecond); - if (!TreeAnalyzer.TryGetPolynomial(above, x, out var monomials)) + return (halves, above, constantBelow, third, order); + } + + /// + /// The coefficients of in , from + /// x^0 up; null where it is not a polynomial or is of a degree past + /// . + /// + private static Entity[]? CoefficientsBesideARoot(Entity polynomial, Entity.Variable x) + { + if (!TreeAnalyzer.TryGetPolynomial(polynomial, x, out var monomials)) return null; var degree = 0; foreach (var pair in monomials) { - if (pair.Key.Sign < 0 || pair.Key.CompareTo(EInteger.FromInt32(MaximumDegreeBesideTwoLinearRoots)) > 0 + if (pair.Key.Sign < 0 || pair.Key.CompareTo(EInteger.FromInt32(MaximumDegreeBesideARoot)) > 0 || pair.Value.ContainsNode(x)) return null; degree = System.Math.Max(degree, pair.Key.ToInt32Unchecked()); } - var t = new Entity[degree + 1]; + var coefficients = new Entity[degree + 1]; for (var j = 0; j <= degree; j++) - t[j] = monomials.TryGetValue(EInteger.FromInt32(j), out var coefficient) ? coefficient : Number.Integer.Zero; - - var q0 = a * c; - var q1 = a * d + b * c; - var q2 = b * d; - var root = MathS.Sqrt(first) / MathS.Sqrt(second); + coefficients[j] = monomials.TryGetValue(EInteger.FromInt32(j), out var coefficient) ? coefficient : Number.Integer.Zero; + return coefficients; + } - // Around the third linear's root, a symbol xi stands for -g/h until the end, so that - // what is computed is polynomial in it: T/(g + h x)^k is T/(h^k (x - xi)^k), and with + /// + /// The integral of T(x)/((g + h x)^k S), T a polynomial with the coefficients + /// and S a square root of Q = q0 + q1 x + q2 x^2, by + /// undetermined coefficients: the algebraic terms, which the caller multiplies by + /// S; a multiple of int 1/S; and with the linear, a multiple of + /// int 1/((g + h x) S). Null where a coefficient is not written back in the + /// symbols. + /// + /// + /// + /// All this uses of S is S' = Q'/(2 S), which holds because + /// sqrt(z)^2 = z for every complex z, so S may be the root of Q or + /// a product of the roots of its factors. + /// + /// + /// The polynomial part. In powers of y = g + h x, the terms of T from + /// y^k up leave a polynomial R(x), and + /// int R/S = U S + lambda int 1/S. The derivative of U S is + /// (U' Q + U Q'/2)/S, so R = U' Q + U Q'/2 + lambda, which for U of one + /// degree less than R is triangular. The coefficient of x^j on the right is + /// (j + 1) q0 u_(j+1) + (j + 1/2) q1 u_j + j q2 u_(j-1). That is solved for + /// u_(j-1) from the top down, and lambda is what is left at x^0. + /// + /// + /// The terms over powers of y. With xi = -g/h and s = x - xi, write + /// Q = alpha + beta s + gamma s^2. The derivative of S s^(1-j) is + /// (2 (1 - j) alpha s^(-j) + (3 - 2j) beta s^(1-j) + (4 - 2j) gamma s^(2-j)) / (2 S). + /// So for j >= 2, I_j = int 1/(s^j S) is given by S s^(1-j) and the two + /// integrals before it, and all the way down it is algebraic terms and a multiple of + /// I_1, where alpha, the value of Q at the root of y, is not zero. + /// Where it is, the linear shares a root with Q, and the derivative of + /// S s^(-j) is ((1 - 2j) beta s^(-j) + (2 - 2j) gamma s^(1-j)) / (2 S): then + /// every I_j is algebraic, from I_1 = -2 S/(beta s) up, and there is no + /// third integral. + /// + /// + /// Back in the symbols. A symbol stands for xi until the end, so that what + /// is computed is polynomial in it, and alpha^(k-1), or beta^k beside a shared + /// root, is divided by once. Each coefficient is then written homogeneous in g and + /// h, with the powers of h counted, over the factors the caller writes + /// h^2 alpha or h beta as: 's AtThePole. The multiple of int 1/S is divided by + /// first, where there is one, and the multiple of + /// int 1/(y S) by the factor names: the + /// caller's closed forms have them below the bar. + /// + /// + private static (Entity Algebraic, Entity OfTheFirstKind, Entity OfTheThirdKind)? IntegrateOverARootOfAQuadratic( + Entity expr, Entity.Variable x, Entity[] t, Entity q0, Entity q1, Entity q2, System.Func quadraticAt, + ALinearBesideTheRoot? pole, Entity? firstKindOver, int? thirdKindAlsoOver) + { + var degree = t.Length - 1; + // Around the linear's root, a symbol xi stands for -g/h until the end, so that what + // is computed is polynomial in it: T/(g + h x)^k is T/(h^k (x - xi)^k), and with // T = sum tau_i (x - xi)^i its terms from (x - xi)^k up are the polynomial R(x), and the // rest are tau_(k-j)/(x - xi)^j. Variable? xi = null; - Entity? g = null; - Entity? h = null; - Entity? firstAtThePole = null; - Entity? secondAtThePole = null; + var order = 0; var polynomial = t; var overThePole = new SortedDictionary(); Entity ofTheThirdKind = Number.Integer.Zero; - if (third is { }) + // What the coefficients over the pole are divided by: a power of each factor of + // h^2 alpha, or of h beta, and the powers of h that brings. + var belowThePole = 0; + var hOfThePole = 0; + if (pole is { } linear) { - if (!TreeAnalyzer.TryGetPolyLinear(third, x, out h, out g) || IsZero(h)) - return null; - // h^2 Q at the pole, (h a - g b)(h c - g d): zero where the third linear shares - // a root with one under a root, which is declined. - firstAtThePole = h * a - g * b; - secondAtThePole = h * c - g * d; - if (IsZero(firstAtThePole) || IsZero(secondAtThePole)) + if (linear.AtThePole.Any(IsZeroOverTheSymbols)) return null; + order = linear.Order; xi = Variable.CreateUnique(expr, "pole"); - var alpha = Lowest((a + b * xi) * (c + d * xi)); - var beta = Lowest(q1 + 2 * q2 * xi); + var beta = LowestOverTheSymbols(q1 + 2 * q2 * xi); var gamma = q2; var tau = new Entity[degree + 1]; for (var i = 0; i <= degree; i++) @@ -8569,8 +8767,8 @@ node is Powf(var @base, Number.Rational power) && power is not Number.Integer && Entity sum = Number.Integer.Zero; for (var m = i; m <= degree; m++) if (t[m] != Number.Integer.Zero) - sum = sum + t[m] * Binomial(m, i) * Power(xi, m - i); - tau[i] = Lowest(sum); + sum = sum + t[m] * BinomialCoefficient(m, i) * WholePower(xi, m - i); + tau[i] = LowestOverTheSymbols(sum); } polynomial = new Entity[System.Math.Max(degree - order + 1, 0)]; for (var m = 0; m < polynomial.Length; m++) @@ -8578,46 +8776,77 @@ node is Powf(var @base, Number.Rational power) && power is not Number.Integer && Entity sum = Number.Integer.Zero; for (var i = order + m; i <= degree; i++) if (tau[i] != Number.Integer.Zero) - sum = sum + tau[i] * Binomial(i - order, m) * Power(-xi, i - order - m); - polynomial[m] = Lowest(sum); - } - // I_j = int 1/((x - xi)^j S), with Q = alpha + beta (x - xi) + gamma (x - xi)^2. The - // derivative of S (x - xi)^(1-j) is - // (2 (1 - j) alpha (x - xi)^(-j) + (3 - 2j) beta (x - xi)^(1-j) - // + (4 - 2j) gamma (x - xi)^(2-j)) / (2 S), - // so alpha^(j-1) I_j is a polynomial in xi times powers of x - xi, times S, and a - // polynomial in xi times I_1: divided by alpha only once, at the end. - var scaled = new Dictionary[order + 1]; - var ofTheFirst = new Entity[order + 1]; - scaled[0] = new Dictionary(); - ofTheFirst[0] = Number.Integer.Zero; - if (order >= 1) - { - scaled[1] = new Dictionary(); - ofTheFirst[1] = Number.Integer.One; - } - for (var j = 2; j <= order; j++) - { - var these = new Dictionary { [1 - j] = 2 * Power(alpha, j - 2) }; - foreach (var (earlier, times) in new[] { (scaled[j - 1], (3 - 2 * j) * beta), (scaled[j - 2], (4 - 2 * j) * gamma * alpha) }) - foreach (var pair in earlier) - these[pair.Key] = these.TryGetValue(pair.Key, out var so) ? so - times * pair.Value : -times * pair.Value; - scaled[j] = these.ToDictionary(pair => pair.Key, pair => Lowest(pair.Value / (2 * (1 - j)))); - ofTheFirst[j] = Lowest((-(3 - 2 * j) * beta * ofTheFirst[j - 1] - (4 - 2 * j) * gamma * alpha * ofTheFirst[j - 2]) / (2 * (1 - j))); - } - // sum tau_(k-j) I_j over alpha^(k-1). - for (var j = 1; j <= order; j++) - { - if (order - j > degree || tau[order - j] == Number.Integer.Zero) - continue; - var weight = tau[order - j] * Power(alpha, order - j); - foreach (var pair in scaled[j]) - overThePole[pair.Key] = overThePole.TryGetValue(pair.Key, out var so) ? so + weight * pair.Value : weight * pair.Value; - ofTheThirdKind = ofTheThirdKind + weight * ofTheFirst[j]; + sum = sum + tau[i] * BinomialCoefficient(i - order, m) * WholePower(-xi, i - order - m); + polynomial[m] = LowestOverTheSymbols(sum); + } + if (linear.SharesARoot) + { + // Q = beta (x - xi) + gamma (x - xi)^2, so + // I_j = (2 S (x - xi)^(-j) - (2 - 2j) gamma I_(j-1)) / ((1 - 2j) beta), + // and beta^j I_j is a polynomial in xi times powers of x - xi, times S: sum + // tau_(k-j) I_j over beta^k. + var previous = new Dictionary(); + for (var j = 1; j <= order; j++) + { + var these = new Dictionary { [-j] = 2 * WholePower(beta, j - 1) }; + foreach (var pair in previous) + these[pair.Key] = these.TryGetValue(pair.Key, out var so) + ? so - (2 - 2 * j) * gamma * pair.Value : -(2 - 2 * j) * gamma * pair.Value; + previous = these.ToDictionary(pair => pair.Key, pair => LowestOverTheSymbols(pair.Value / (1 - 2 * j))); + if (order - j > degree || tau[order - j] == Number.Integer.Zero) + continue; + var weight = tau[order - j] * WholePower(beta, order - j); + foreach (var pair in previous) + overThePole[pair.Key] = overThePole.TryGetValue(pair.Key, out var so) ? so + weight * pair.Value : weight * pair.Value; + } + foreach (var power in overThePole.Keys.ToList()) + overThePole[power] = LowestOverTheSymbols(overThePole[power]); + belowThePole = order; + hOfThePole = order; + } + else + { + var alpha = LowestOverTheSymbols(quadraticAt(xi)); + // I_j = int 1/((x - xi)^j S), with Q = alpha + beta (x - xi) + gamma (x - xi)^2. The + // derivative of S (x - xi)^(1-j) is + // (2 (1 - j) alpha (x - xi)^(-j) + (3 - 2j) beta (x - xi)^(1-j) + // + (4 - 2j) gamma (x - xi)^(2-j)) / (2 S), + // so alpha^(j-1) I_j is a polynomial in xi times powers of x - xi, times S, and a + // polynomial in xi times I_1: divided by alpha only once, at the end. + var scaled = new Dictionary[order + 1]; + var ofTheFirst = new Entity[order + 1]; + scaled[0] = new Dictionary(); + ofTheFirst[0] = Number.Integer.Zero; + if (order >= 1) + { + scaled[1] = new Dictionary(); + ofTheFirst[1] = Number.Integer.One; + } + for (var j = 2; j <= order; j++) + { + var these = new Dictionary { [1 - j] = 2 * WholePower(alpha, j - 2) }; + foreach (var (earlier, times) in new[] { (scaled[j - 1], (3 - 2 * j) * beta), (scaled[j - 2], (4 - 2 * j) * gamma * alpha) }) + foreach (var pair in earlier) + these[pair.Key] = these.TryGetValue(pair.Key, out var so) ? so - times * pair.Value : -times * pair.Value; + scaled[j] = these.ToDictionary(pair => pair.Key, pair => LowestOverTheSymbols(pair.Value / (2 * (1 - j)))); + ofTheFirst[j] = LowestOverTheSymbols((-(3 - 2 * j) * beta * ofTheFirst[j - 1] - (4 - 2 * j) * gamma * alpha * ofTheFirst[j - 2]) / (2 * (1 - j))); + } + // sum tau_(k-j) I_j over alpha^(k-1). + for (var j = 1; j <= order; j++) + { + if (order - j > degree || tau[order - j] == Number.Integer.Zero) + continue; + var weight = tau[order - j] * WholePower(alpha, order - j); + foreach (var pair in scaled[j]) + overThePole[pair.Key] = overThePole.TryGetValue(pair.Key, out var so) ? so + weight * pair.Value : weight * pair.Value; + ofTheThirdKind = ofTheThirdKind + weight * ofTheFirst[j]; + } + foreach (var power in overThePole.Keys.ToList()) + overThePole[power] = LowestOverTheSymbols(overThePole[power]); + ofTheThirdKind = LowestOverTheSymbols(ofTheThirdKind); + belowThePole = order - 1; + hOfThePole = 2 * (order - 1); } - foreach (var power in overThePole.Keys.ToList()) - overThePole[power] = Lowest(overThePole[power]); - ofTheThirdKind = Lowest(ofTheThirdKind); } // The polynomial part: u_(j-1) from the top down, and lambda at x^0. @@ -8629,7 +8858,7 @@ node is Powf(var @base, Number.Rational power) && power is not Number.Integer && { var n = polynomial.Length - 1; for (var j = n; j >= 1; j--) - u[j - 1] = Lowest((polynomial[j] - (j + 1) * q0 * u[j + 1] - Number.Rational.Create(2 * j + 1, 2) * q1 * u[j]) / (j * q2)); + u[j - 1] = LowestOverTheSymbols((polynomial[j] - (j + 1) * q0 * u[j + 1] - Number.Rational.Create(2 * j + 1, 2) * q1 * u[j]) / (j * q2)); lambda = polynomial[0] - q0 * u[1] - q1 * u[0] / 2; } @@ -8637,104 +8866,151 @@ node is Powf(var @base, Number.Rational power) && power is not Number.Integer && // polynomial in xi, written homogeneous in g and h with the powers of h counted: // substituted as it stands, each term would bring its own power of h below the bar, // and over one bar they multiply. - Entity? Back(Entity coefficient, int powerOfH, int belowAtThePole, int belowTheFirst) + Entity? Back(Entity coefficient, int powerOfH, int[] overTheFactors) { - var (above, below) = Functions.SingleQuotient.Of(Lowest(coefficient)); + var (above, below) = Functions.SingleQuotient.Of(LowestOverTheSymbols(coefficient)); if (xi is null) - return Lowest(above / below); + return LowestOverTheSymbols(above / below); if (Homogeneous(above) is not var (aboveInGAndH, aboveDegree) || Homogeneous(below) is not var (belowInGAndH, belowDegree)) return null; + var h = pole!.H; var power = powerOfH + belowDegree - aboveDegree - order; - var numerator = Lowest(power > 0 ? aboveInGAndH * Power(h!, power) : aboveInGAndH); + var numerator = LowestOverTheSymbols(power > 0 ? aboveInGAndH * WholePower(h, power) : aboveInGAndH); if (numerator == Number.Integer.Zero) return Number.Integer.Zero; - var denominator = Lowest(power < 0 ? belowInGAndH * Power(h!, -power) : belowInGAndH); - // alpha^(k-1) at the pole is ((h a - g b)(h c - g d))^(k-1)/h^(2 (k - 1)), its powers - // of h counted in powerOfH; the two linears are left as written. - Entity written = denominator * Power(firstAtThePole!, belowTheFirst) * Power(secondAtThePole!, belowAtThePole); - var lowest = Lowest(numerator / written); + var denominator = LowestOverTheSymbols(power < 0 ? belowInGAndH * WholePower(h, -power) : belowInGAndH); + // alpha^(k-1) is (h^2 alpha)^(k-1)/h^(2 (k - 1)), and beta^k is (h beta)^k/h^k, their + // powers of h counted in powerOfH, and h^2 alpha or h beta left in the factors the + // caller writes it as. + Entity written = denominator; + for (var i = 0; i < overTheFactors.Length; i++) + written = written * WholePower(pole.AtThePole[i], overTheFactors[i]); + var lowest = LowestOverTheSymbols(numerator / written); return lowest.Complexity <= (numerator / written).Complexity ? lowest : numerator / written; } - (Entity, int)? Homogeneous(Entity polynomial) + (Entity, int)? Homogeneous(Entity inXi) { - if (!TreeAnalyzer.TryGetPolynomial(polynomial, xi!, out var byPower) || byPower.Keys.Any(power => power.Sign < 0 || !power.CanFitInInt32())) + if (!TreeAnalyzer.TryGetPolynomial(inXi, xi!, out var byPower) || byPower.Keys.Any(power => power.Sign < 0 || !power.CanFitInInt32())) return null; + var (_, g, h, _, _, _) = pole!; var top = byPower.Keys.Max()!.ToInt32Unchecked(); Entity sum = Number.Integer.Zero; foreach (var pair in byPower) - sum = sum + pair.Value * Power(-g!, pair.Key.ToInt32Unchecked()) * Power(h!, top - pair.Key.ToInt32Unchecked()); - return (Lowest(sum), top); + sum = sum + pair.Value * WholePower(-g, pair.Key.ToInt32Unchecked()) * WholePower(h, top - pair.Key.ToInt32Unchecked()); + return (LowestOverTheSymbols(sum), top); } + var factors = pole?.AtThePole.Length ?? 0; Entity algebraic = Number.Integer.Zero; for (var j = u.Length - 1; j >= 0; j--) if (u[j] != Number.Integer.Zero) { - if (Back(u[j], 0, 0, 0) is not { } coefficient) + if (Back(u[j], 0, new int[factors]) is not { } coefficient) return null; if (coefficient != Number.Integer.Zero) - algebraic = algebraic + coefficient * Power(x, j); + algebraic = algebraic + coefficient * WholePower(x, j); } - // (x - xi)^p is h^(-p) (g + h x)^p, and 1/alpha^(k-1) brings h^(2 (k - 1)). + // (x - xi)^p is h^(-p) (g + h x)^p. + var overThePoleFactors = Enumerable.Repeat(belowThePole, factors).ToArray(); foreach (var pair in overThePole) { - if (Back(pair.Value, -pair.Key + 2 * (order - 1), order - 1, order - 1) is not { } coefficient) + if (Back(pair.Value, -pair.Key + hOfThePole, overThePoleFactors) is not { } coefficient) return null; if (coefficient != Number.Integer.Zero) - algebraic = algebraic + coefficient / Power(third!, -pair.Key); + algebraic = algebraic + coefficient / WholePower(pole!.Linear, -pair.Key); } - var answer = algebraic * MathS.Sqrt(first) * MathS.Sqrt(second); + Entity ofTheFirstKind = Number.Integer.Zero; if (lambda != Number.Integer.Zero) { - if (Back(lambda / b, 0, 0, 0) is not { } ofTheLogarithm) + if (Back(firstKindOver is null ? lambda : lambda / firstKindOver, 0, new int[factors]) is not { } coefficient) return null; - // int 1/S, with 2 artanh(z) written as the logarithm the library writes it as. - var r = Lowest(d / b); - if (ofTheLogarithm != Number.Integer.Zero) - answer = answer + BySign(r, - ofTheLogarithm * MathS.Ln((1 + MathS.Sqrt(r) * root) / (1 - MathS.Sqrt(r) * root)) / MathS.Sqrt(r), - 2 * ofTheLogarithm * MathS.Arctan(MathS.Sqrt(-r) * root) / MathS.Sqrt(-r)); + ofTheFirstKind = coefficient; } + // int 1/((x - xi) S) is h int 1/(y S). + Entity thirdKind = Number.Integer.Zero; if (xi is { } && ofTheThirdKind != Number.Integer.Zero) { - // int 1/((x - xi) S) is h I_1, and I_1 = -2 arctan(sqrt(rho) t)/((h a - g b) sqrt(rho)) with - // rho = (g d - h c)/(h a - g b). - if (Back(ofTheThirdKind, 2 * (order - 1) + 1, order - 1, order) is not { } coefficient) + if (thirdKindAlsoOver is { } factor) + overThePoleFactors[factor]++; + if (Back(ofTheThirdKind, hOfThePole + 1, overThePoleFactors) is not { } coefficient) return null; - var rho = Lowest(-secondAtThePole! / firstAtThePole!); - if (coefficient != Number.Integer.Zero) - answer = answer + BySign(rho, - -2 * coefficient * MathS.Arctan(MathS.Sqrt(rho) * root) / MathS.Sqrt(rho), - -coefficient * MathS.Ln((1 + MathS.Sqrt(-rho) * root) / (1 - MathS.Sqrt(-rho) * root)) / MathS.Sqrt(-rho)); + thirdKind = coefficient; } - return (constantBelow == Number.Integer.One ? answer : answer / constantBelow).InnerSimplified; + return (algebraic, ofTheFirstKind, thirdKind); + } - static Entity Lowest(Entity e) => Functions.PartialFractions.InLowestTermsOverTheSymbols(e); - // Each closed form is real on one side of the sign of the quantity under its roots, and - // complex by a constant on the other: the form for the sign of a number, and both, each - // where it holds, for a quantity with symbols in it, as `1/(a - x^2)` is answered. - static Entity BySign(Entity quantity, Entity wherePositive, Entity whereNegative) - => !quantity.Vars.Any() && quantity.InnerSimplified is Number.Real number - ? (number.IsNegative ? whereNegative : wherePositive) - : MathS.Piecewise((wherePositive, new Greaterf(quantity, Number.Integer.Zero)), (whereNegative, new Lessf(quantity, Number.Integer.Zero))); - static bool IsZero(Entity e) => e.InnerSimplified is var simplified - && (simplified.Evaled is Number.Complex { IsZero: true } || simplified.Vars.Any() && Lowest(simplified) == Number.Integer.Zero); - // Not e^0, which is 1 only where e is not 0, and says so. - static Entity Power(Entity e, int n) => n switch { 0 => Number.Integer.One, 1 => e, _ => MathS.Pow(e, n) }; - static Entity Binomial(int n, int k) - { - var result = EInteger.One; - for (var i = 1; i <= k; i++) - result = result.Multiply(EInteger.FromInt32(n - k + i)).Divide(EInteger.FromInt32(i)); - return Number.Integer.Create(result); - } + /// + /// The linear below the bar beside the root of a quadratic Q, for + /// : as written, g + h x, to the power + /// Order. AtThePole holds the factors the caller writes h^2 Q(-g/h) as, + /// or where that is zero and the linear shares a root with Q, h Q'(-g/h). + /// + private sealed record ALinearBesideTheRoot(Entity Linear, Entity G, Entity H, int Order, Entity[] AtThePole, bool SharesARoot); + + private static Entity LowestOverTheSymbols(Entity e) => Functions.PartialFractions.InLowestTermsOverTheSymbols(e); + + // Each closed form is real on one side of the sign of the quantity under its roots, and + // complex by a constant on the other: the form for the sign of a number, and both, each + // where it holds, for a quantity with symbols in it, as `1/(a - x^2)` is answered. A + // number times even powers of symbols has the number's sign wherever the symbols are + // real and not zero, which is the generic case: `-b^2` in `a^2 - b^2 x^2` is negative. + private static Entity BySign(Entity quantity, Entity wherePositive, Entity whereNegative) + => SignOfANumberTimesEvenPowers(quantity) is { } sign + ? (sign < 0 ? whereNegative : wherePositive) + : MathS.Piecewise((wherePositive, new Greaterf(quantity, Number.Integer.Zero)), (whereNegative, new Lessf(quantity, Number.Integer.Zero))); + + // The same where the form for a positive first quantity is chosen by the sign of a second, + // as one piecewise rather than one inside another. + private static Entity BySigns(Entity first, Entity second, Entity wherePositiveAndPositive, Entity wherePositiveAndNegative, Entity whereNegative) + { + var wherePositive = BySign(second, wherePositiveAndPositive, wherePositiveAndNegative); + if (wherePositive is not Piecewise || SignOfANumberTimesEvenPowers(first) is { }) + return BySign(first, wherePositive, whereNegative); + var positive = new Greaterf(first, Number.Integer.Zero); + return MathS.Piecewise( + (wherePositiveAndPositive, new Andf(positive, new Greaterf(second, Number.Integer.Zero))), + (wherePositiveAndNegative, new Andf(positive, new Lessf(second, Number.Integer.Zero))), + (whereNegative, new Lessf(first, Number.Integer.Zero))); + } + + private static int? SignOfANumberTimesEvenPowers(Entity quantity) + { + var sign = 1; + foreach (var factor in Mulf.LinearChildren(quantity.InnerSimplified)) + switch (factor) + { + case Number.Real { IsZero: true }: + return null; + case Number.Real number: + sign *= number.IsNegative ? -1 : 1; + break; + case Powf(Variable, Number.Integer power) when power.EInteger.IsEven && !power.EInteger.IsZero: + break; + default: + return null; + } + return sign; + } + + private static bool IsZeroOverTheSymbols(Entity e) => e.InnerSimplified is var simplified + && (simplified.Evaled is Number.Complex { IsZero: true } || simplified.Vars.Any() && LowestOverTheSymbols(simplified) == Number.Integer.Zero); + + // Not e^0, which is 1 only where e is not 0, and says so. + private static Entity WholePower(Entity e, int n) => n switch { 0 => Number.Integer.One, 1 => e, _ => MathS.Pow(e, n) }; + + private static Entity BinomialCoefficient(int n, int k) + { + var result = EInteger.One; + for (var i = 1; i <= k; i++) + result = result.Multiply(EInteger.FromInt32(n - k + i)).Divide(EInteger.FromInt32(i)); + return Number.Integer.Create(result); } /// - /// The degree of the polynomial - /// solves for: one unknown a degree, and Rubi's 1.1.1.6 reaches eight. + /// The degree of the polynomial solves for: + /// one unknown a degree. Rubi's 1.1.1.6 reaches eight, and 1.2.1.9 ten. /// - private const int MaximumDegreeBesideTwoLinearRoots = 16; + private const int MaximumDegreeBesideARoot = 16; /// /// Whether is a quotient of two polynomials linear in diff --git a/Sources/AngouriMath/Functions/Continuous/Integration/Integration.Definition.cs b/Sources/AngouriMath/Functions/Continuous/Integration/Integration.Definition.cs index f086ea50f..0058ebd66 100644 --- a/Sources/AngouriMath/Functions/Continuous/Integration/Integration.Definition.cs +++ b/Sources/AngouriMath/Functions/Continuous/Integration/Integration.Definition.cs @@ -752,6 +752,8 @@ private static Entity Normalized(Entity expr, Entity.Variable x) => // `(A + B x + C x^2) sqrt(c + d x) sqrt(e + f x)` by undetermined coefficients, // where the substitution further down took gigabytes. if ((answer = IndefiniteIntegralSolver.SolveAPolynomialOverAPowerOfALinearBesideTwoRoots(expr, x)) is { }) return answer; + // And beside the root of one quadratic: `(d + e x + f x^2) sqrt(a + c x^2)/(g + h x)^4`. + if ((answer = IndefiniteIntegralSolver.SolveAPolynomialOverAPowerOfALinearBesideARootOfAQuadratic(expr, x)) is { }) return answer; // A square root of a polynomial with a repeated factor, the factor taken out of // the root with its sign: `sqrt((x - 3)^2 (x + 1))` is `sgn(x - 3) (x - 3) sqrt(x + 1)`. if ((answer = IndefiniteIntegralSolver.SolveByTakingASquareFactorOutOfARoot(expr, x, integrateByParts)) is { }) return answer; diff --git a/Sources/Tests/UnitTests/Calculus/PowerOfALinearBesideTheRootOfAQuadraticTest.cs b/Sources/Tests/UnitTests/Calculus/PowerOfALinearBesideTheRootOfAQuadraticTest.cs new file mode 100644 index 000000000..e13f60cac --- /dev/null +++ b/Sources/Tests/UnitTests/Calculus/PowerOfALinearBesideTheRootOfAQuadraticTest.cs @@ -0,0 +1,147 @@ +// +// 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 AngouriMath.Extensions; +using Xunit; + +namespace AngouriMath.Tests.Calculus +{ + /// + /// A polynomial over a power of a linear beside a half-odd power of a quadratic, Rubi's + /// 1.2.1.9, by undetermined coefficients: algebraic terms times the root, and multiples of + /// the integrals of 1/sqrt(Q) and 1/((g + h x) sqrt(Q)). + /// #718 + /// + /// + /// Checked by differentiating back at points where the integrand is real, never against a + /// printed form. With symbols, each of the two integrals is a piecewise on the sign of a + /// quantity, so each row is checked with the symbols pinned on both sides of it. + /// + [Trait("Area", "Calculus")] + public sealed class PowerOfALinearBesideTheRootOfAQuadraticTest + { + private static void DifferentiatesBack(string integrand, double[] points, params (string, double)[] pins) + { + var integral = integrand.ToEntity().Integrate("x"); + Assert.DoesNotContain("integral(", integral.Stringize()); + + var derivative = integral.Substitute("C", 0).Differentiate("x"); + Entity original = integrand.ToEntity(); + foreach (var (name, value) in pins) + { + derivative = derivative.Substitute(name, value); + original = original.Substitute(name, value); + } + var compared = 0; + foreach (var at in points) + { + var got = derivative.Substitute("x", at).EvalNumerical(); + var want = original.Substitute("x", at).EvalNumerical(); + if (got.IsNaN || want.IsNaN) + continue; + compared++; + 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 the antiderivative of {integrand} is {got} at x = {at}, " + + $"where the integrand is {want}"); + } + Assert.True(compared >= 3, $"only {compared} points could be compared for {integrand}"); + } + + public static TheoryData Symbolic => new() + { + "(d + k*x + f*x^2)*sqrt(a + c*x^2)/(g + h*x)^4", + "(a + c*x^2)^(3/2)*(d + k*x + f*x^2)/(g + h*x)^3", + "(d + k*x + f*x^2)*sqrt(a + b*x + c*x^2)/(g + h*x)^3", + "(a + b*x + c*x^2)^(3/2)*(d + k*x + f*x^2)/(g + h*x)^2", + "(d + k*x + f*x^2)/((g + h*x)^2*sqrt(a + b*x + c*x^2))", + // A first power, which the rules for a linear beside the root declined. + "1/((g + h*x)*sqrt(a + c*x^2))", + "(d + k*x + f*x^2)*sqrt(a + c*x^2)/(g + h*x)", + }; + + /// + /// The leading coefficient positive, and the quadratic positive at the linear's root: + /// both integrals are logarithms. + /// + [Theory] + [MemberData(nameof(Symbolic))] + public void BothLogarithms(string integrand) + => DifferentiatesBack(integrand, new[] { 0.3, 0.9, 1.7, 2.6 }, + ("a", 1.3), ("b", 0.7), ("c", 0.8), ("d", 1.1), ("k", -0.6), ("f", 0.45), ("g", 1.9), ("h", 0.5)); + + /// + /// The leading coefficient negative, so the integral of 1/sqrt(Q) is an arcsine, + /// and the quadratic negative at the linear's root, so the other is an arctangent: the + /// quadratic is real between its roots, near -1.8 and 2.6, and the linear's is at -3.5. + /// + [Theory] + [MemberData(nameof(Symbolic))] + public void AnArcsineAndAnArctangent(string integrand) + => DifferentiatesBack(integrand, new[] { -1.2, 0.3, 0.9, 1.7, 2.2 }, + ("a", 2.3), ("b", 0.4), ("c", -0.5), ("d", 1.1), ("k", -0.6), ("f", 0.45), ("g", 3.5), ("h", 1)); + + /// + /// The linear sharing a root with the quadratic, where every integral over a power of + /// the linear is algebraic: (d + m x)(a m + c d x) written out, as Rubi writes + /// it, and d^2 - m^2 x^2, real between its roots near -1.8 and 1.8. + /// + [Theory] + [InlineData("(a*d*m + (c*d^2 + a*m^2)*x + c*d*m*x^2)^(5/2)/(d + m*x)^4", new[] { 0.3, 0.9, 1.7, 2.6 })] + [InlineData("sqrt(a*d*m + (c*d^2 + a*m^2)*x + c*d*m*x^2)/(d + m*x)^3", new[] { 0.3, 0.9, 1.7, 2.6 })] + [InlineData("(A + B*x + F*x^2)*sqrt(d^2 - m^2*x^2)/(d + m*x)^2", new[] { -1.2, 0.3, 0.9, 1.7 })] + [InlineData("(A + B*x + F*x^2)/((d + m*x)^3*sqrt(d^2 - m^2*x^2))", new[] { -1.2, 0.3, 0.9, 1.7 })] + [InlineData("sqrt(1 - x^2)/(1 + x)^2", new[] { -0.6, 0.3, 0.9 })] + public void BesideASharedRoot(string integrand, double[] points) + => DifferentiatesBack(integrand, points, + ("a", 1.3), ("c", 0.8), ("d", 1.1), ("m", 0.6), ("A", 0.7), ("B", -0.4), ("F", 0.9)); + + /// + /// The antiderivative is real wherever the integrand is, and not real by a constant: a + /// differentiation back cannot see a constant. The logarithm over the linear's root is of + /// (1 + z)/(1 - z) where the quadratic has no real root and of (z + 1)/(z - 1) + /// where it has two, and each row is on one side, the symbolic ones pinned to it. + /// + [Theory] + [InlineData("sqrt(4 - x^2)/x^3", new[] { 0.3, 0.9, 1.7 }, new string[0], new double[0])] + [InlineData("sqrt(1 + x^2)/(1 + x)^2", new[] { -2.6, 0.3, 0.9, 1.7 }, new string[0], new double[0])] + [InlineData("1/((g + h*x)*sqrt(a + c*x^2))", new[] { -1.2, 0.3, 0.9, 1.7 }, new[] { "a", "c", "g", "h" }, new[] { 1.3, 0.8, 1.9, 0.5 })] + [InlineData("1/((g + h*x)*sqrt(a + c*x^2))", new[] { -2.6, 1.5, 2.0, 2.6 }, new[] { "a", "c", "g", "h" }, new[] { -1.2, 0.8, 1.9, 0.5 })] + public void RealWhereTheIntegrandIsReal(string integrand, double[] points, string[] names, double[] values) + { + var integral = integrand.ToEntity().Integrate("x").Substitute("C", 0); + Entity original = integrand.ToEntity(); + for (var i = 0; i < names.Length; i++) + { + integral = integral.Substitute(names[i], values[i]); + original = original.Substitute(names[i], values[i]); + } + foreach (var at in points) + { + var want = original.Substitute("x", at).EvalNumerical(); + Assert.True(!want.IsNaN && Math.Abs((double)want.ImaginaryPart) < 1e-12, $"{integrand} is not real at x = {at}"); + var got = integral.Substitute("x", at).EvalNumerical(); + Assert.True(!got.IsNaN && Math.Abs((double)got.ImaginaryPart) < 1e-9, + $"the antiderivative of {integrand} is {got} at x = {at}, where the integrand is real"); + } + } + + /// + /// Rubi's rows with numbers, which nothing answered: the rules further down take a + /// product of distinct linears apart beside the root, and not a power of one. + /// + [Theory] + [InlineData("(2 + x + 3*x^2 - x^3 + 5*x^4)*sqrt(3 - x + 2*x^2)/(5 + 2*x)^5")] + [InlineData("(3 - x + 2*x^2)^(3/2)*(2 + x + 3*x^2 - x^3 + 5*x^4)/(5 + 2*x)^2")] + [InlineData("(2 + x + 3*x^2 - x^3 + 5*x^4)/((5 + 2*x)^4*sqrt(3 - x + 2*x^2))")] + [InlineData("(1 + 3*x + 4*x^2)*sqrt(2 - x + 3*x^2)/(1 + 2*x)^3")] + public void WithNumbers(string integrand) + => DifferentiatesBack(integrand, new[] { -1.7, 0.3, 0.9, 1.7, 2.6 }); + } +}