Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -421,8 +421,16 @@ private static bool TryDivideMonomials(ulong dividend, ulong divisor, int variab
/// that reads the way the answer is usually written: <c>x + y</c>, not
/// <c>-x/2 - y/2</c>.
/// </remarks>
internal MultivariatePolynomial Normalized()
internal MultivariatePolynomial Normalized() => Normalized(out _);

/// <summary>
/// <see cref="Normalized()"/>, with the factor it was scaled by: the normalized
/// polynomial is this one times <paramref name="scale"/>, and this one is the
/// normalized one over it.
/// </summary>
internal MultivariatePolynomial Normalized(out ERational scale)
{
scale = ERational.One;
if (IsZero)
return this;
var denominators = EInteger.One;
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

/// <summary>
/// The largest value of the elimination, by <see cref="Entity.Complexity"/>, 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.
/// </summary>
private const int LargestValuePutInLowestTerms = 4096;

/// <summary>
/// <c>N/D</c> written as one fraction per factor of <paramref name="denominator"/>,
/// where the denominator is <b>written</b> as a product of distinct linear and quadratic
Expand Down Expand Up @@ -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++)
{
Expand Down Expand Up @@ -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);
}

/// <summary>
/// <paramref name="quotient"/> 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. <c>-1024/(1024 a)</c> is
/// <c>-1/a</c>.
/// </summary>
/// <remarks>
/// 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 <c>1024/1024</c>
/// after the first round was integers of twelve hundred digits after the third and
/// a minute of gcd on them for <c>tanh(x)^6/(a + a sech(x))</c>, which is a sum of
/// small fractions.
/// https://github.com/asc-community/AngouriMath/issues/718
/// </remarks>
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<Variable, int>(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);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,39 @@ public void ARepeatedSymbolicQuadraticBesideALinear(string integrand, int atMost
Assert.True(length < atMost, $"{length} characters of answer for {integrand}");
}

/// <summary>
/// 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 <c>-1024/(1024 a)</c> stayed as it was, and Newton's
/// iteration for the inverse modulo <c>(1 + u^2)^6</c>, which squares its iterate every
/// round, had integers of twelve hundred digits by the third round and spent its
/// minute in their gcd: <c>tanh(x)^6/(a + a sech(x))</c> 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: <c>csch(x)^5/(a + b cosh(x))</c>, after
/// the Hermite reduction under <c>u = e^x</c>, had two thousand nodes of <c>a</c> and
/// <c>b</c> 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
/// <c>a (1 + u^2) + 2 a u</c> out, the denominator is a rational one with <c>a</c> in
/// front, whose <c>(1 + u)^2</c> the refactoring over the rationals reads, and the
/// answer is a page shorter than the split's.
/// </summary>
[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));
}

/// <summary>
/// Two linear factors with one root are one factor: <c>(a + b x)(a + x b)^2</c> is
/// how the rules that make a factor monic and gather its powers write it, and as
Expand Down
Loading