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
9 changes: 9 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4826,6 +4826,15 @@ And what cannot be compiled is named rather than failing obscurely.

Not behavioural changes, listed so that a reader working through this file has the whole picture.

- **Integrals wanting a substitution by a power of the variable that occurs nowhere.**
`int x / (x^4 + 1)` is `arctan(x^2)/2 + C`, and so for `x/(x^4 - 1)`, `x/(x^4 + 4)`,
`x^2/(x^6 + 1)`, `x/(x^6 + 1)`, `x^3/(x^8 + 1)` and `x^3/(x^12 + 1)`. Each was previously
returned unevaluated. Two things had to change: `x^2` is now offered as a candidate although
it is written nowhere in `x / (x^4 + 1)`, and substituting it rewrites `x^4` as `(x^2)^2` so
that there is something for it to replace. `int x^3 / (x^4 + 1)` worked throughout, its own
substitution being one that occurs, which is what made the gap hard to see. No integral that
was answered before is answered differently.
[#233](https://github.com/asc-community/AngouriMath/issues/233).
- **A modulus node.** `Modf`, `MathS.Mod`, the `%` operator on `Entity` in C# and F#, the `mod`
keyword in the parser, evaluation, simplification, differentiation, limits, both compilers, LaTeX
and SymPy export. `a % b` on `Entity` is *not* `int`'s `%` — it is floored, and its documentation
Expand Down
3 changes: 3 additions & 0 deletions Sources/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
[AngouriMath/Functions/Algebra/Polynomials/KroneckerFactorization.cs]
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n

[Tests/UnitTests/Calculus/PowerSubstitutionIntegralTest.cs]
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n

[AngouriMath/Functions/Algebra/Polynomials/FractionFreeDeterminant.cs]
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ arg is Entity.Powf(var y, var pow) ? // log(b, y^p) = ln(y^p) / ln(b) = ln(p) /

// Try to divide expr by duDx and check if result is independent of x
// Replace all occurrences of u's expression with a temporary variable
var integrandInU = (expr / duDx).Substitute(u, uSub).Simplify(1);
var integrandInU = InTermsOf(expr / duDx, u, uSub, x).Simplify(1);
if (integrandInU is Providedf(var innerExpr, _)) integrandInU = innerExpr; // TODO: singularities ignored but not handled properly

// If the result doesn't contain x anymore, we found a valid substitution
Expand All @@ -241,6 +241,53 @@ arg is Entity.Powf(var y, var pow) ? // log(b, y^p) = ln(y^p) / ln(b) = ln(p) /
return null;
}

/// <summary>
/// <paramref name="expr"/> written in terms of <paramref name="uSub"/>, where that stands
/// for <paramref name="u"/>.
/// </summary>
/// <remarks>
/// <para>
/// Ordinarily that is a plain substitution: the candidate occurs in the integrand, and
/// replacing it is all that is wanted.
/// </para>
/// <para>
/// <b>A power of the variable is the exception, and it is the one that mattered.</b>
/// Substituting <c>u = x^2</c> into <c>x / (x^4 + 1)</c> replaces nothing, because
/// <c>x^4</c> is not written as <c>(x^2)^2</c> and a substitution matches what is
/// written. So the integrand kept its <c>x</c>, the candidate was rejected, and
/// <c>int x / (x^4 + 1)</c> came back unevaluated while <c>int x^3 / (x^4 + 1)</c> —
/// whose substitution does occur — did not.
/// <a href="https://github.com/asc-community/AngouriMath/issues/233">#233</a>
/// </para>
/// <para>
/// So a power substitution rewrites the other powers of the variable into powers of
/// itself, which it can do exactly when its exponent divides theirs. Nothing is assumed
/// by it: the caller still checks that no <c>x</c> survives, so a rewrite that does not
/// clear the variable leaves the candidate rejected as before — which is what happens to
/// <c>x^2 / (x^4 + 1)</c>, where a bare <c>x</c> remains and the integral genuinely needs
/// a factorisation this does not have.
/// </para>
/// </remarks>
private static Entity InTermsOf(Entity expr, Entity u, Entity.Variable uSub, Entity.Variable x)
{
if (u is not Powf(var powerBase, Number.Integer exponent)
|| powerBase != x
|| !exponent.EInteger.CanFitInInt32())
return expr.Substitute(u, uSub);
var k = exponent.EInteger.ToInt32Checked();
if (k < 2)
return expr.Substitute(u, uSub);
return expr.Replace(node =>
node is Powf(var otherBase, Number.Integer otherExponent)
&& otherBase == x
&& otherExponent.EInteger.CanFitInInt32()
&& otherExponent.EInteger.ToInt32Checked() is var n
&& n >= k
&& n % k == 0
? (n == k ? uSub : MathS.Pow(uSub, n / k))
: node);
}

/// <summary>
/// Finds potential substitution candidates u = g(x) from the expression.
/// For example, common patterns to try:
Expand All @@ -261,6 +308,20 @@ private static IEnumerable<Entity> FindSubstitutionCandidates(Entity expr, Entit
break;
case Powf(var @base, var exp):
if (@base == x) candidates.Add(node); // Power expressions x^n
// And the roots of that power, which need not occur anywhere to be the
// right substitution: `int x / (x^4 + 1)` wants u = x^2, and x^2 appears
// nowhere in it. A divisor of the exponent is the condition for the
// rewrite to be exact -- see InTermsOf -- so the candidates are exactly
// the divisors, and each is still tested by whether it clears the
// variable. https://github.com/asc-community/AngouriMath/issues/233
if (@base == x
&& exp is Number.Integer power
&& power.EInteger.CanFitInInt32()
&& power.EInteger.ToInt32Checked() is var n
&& n > 2)
for (var divisor = 2; divisor + divisor <= n; divisor++)
if (n % divisor == 0)
candidates.Add(MathS.Pow(x, divisor));
// Exponential with non-trivial argument
if (@base != x && @base.ContainsNode(x)) candidates.Add(@base);
if (exp != x && exp.ContainsNode(x)) candidates.Add(exp);
Expand Down
131 changes: 131 additions & 0 deletions Sources/Tests/UnitTests/Calculus/PowerSubstitutionIntegralTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
//
// 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
{
/// <summary>
/// Integrals that need a substitution by a <em>power of the variable</em> which does not occur
/// anywhere in the integrand.
/// <a href="https://github.com/asc-community/AngouriMath/issues/233">#233</a>
/// </summary>
/// <remarks>
/// <para>
/// <c>int x / (x^4 + 1)</c> wants <c>u = x^2</c>, and <c>x^2</c> is written nowhere in it. Two
/// things followed from that. The candidate was never offered, because candidates were taken
/// from the subexpressions that occur; and had it been, substituting it would have replaced
/// nothing, because <c>x^4</c> is not written as <c>(x^2)^2</c> and a substitution matches
/// what is written. So the integrand kept its <c>x</c> and the candidate was rejected.
/// </para>
/// <para>
/// <c>int x^3 / (x^4 + 1)</c> worked throughout, which is what made this hard to see: its
/// substitution, <c>u = x^4</c>, does occur.
/// </para>
/// <para>
/// Every case here is checked by differentiating the answer and comparing it with the
/// integrand at sampled points, not by comparing printed forms. An antiderivative is only
/// correct if it differentiates back, and these come out with radicals and arctangents whose
/// printed shape says nothing about whether they do.
/// </para>
/// </remarks>
[Trait("Area", "Calculus")]
public sealed class PowerSubstitutionIntegralTest
{
/// <summary>
/// The sample points, chosen away from the poles of the integrands below and on both
/// sides of zero, since a substitution by an even power is where a sign is most easily
/// lost.
/// </summary>
private static readonly double[] Points = { 0.3, 0.7, 1.3, 1.9, 2.6, 3.4, -0.4, -1.7, -2.9 };

private static void DifferentiatesBack(string integrand)
{
var integral = integrand.ToEntity().Integrate("x");
Assert.DoesNotContain("integral(", integral.Stringize());

var derivative = integral.Differentiate("x");
var original = integrand.ToEntity();
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);
var scale = Math.Max(1.0, Math.Abs((double)want.RealPart));
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 >= 5,
$"only {compared} of {Points.Length} points were comparable for {integrand}, "
+ "so this asserts almost nothing");
}

/// <summary>
/// The shape the issue is about: an odd power over an even one, where the substitution is
/// the root of the denominator's power.
/// </summary>
[Theory]
[InlineData("x/(x^4 + 1)")]
[InlineData("x/(x^4 - 1)")]
[InlineData("x/(x^4 + 4)")]
[InlineData("x^2/(x^6 + 1)")]
[InlineData("x/(x^6 + 1)")]
[InlineData("x^3/(x^8 + 1)")]
[InlineData("x^3/(x^12 + 1)")]
public void APowerOfTheVariableThatOccursNowhereIsStillASubstitution(string integrand)
=> DifferentiatesBack(integrand);

/// <summary>
/// <c>int x / (x^4 + 1)</c> is <c>arctan(x^2)/2</c>, which is worth asserting as a form
/// and not only as a derivative: it is the answer the issue's link gives, and getting a
/// constant factor wrong would still differentiate back to something proportional.
/// </summary>
[Fact]
public void TheAnswerIsTheOneTheIssueNames()
{
var integral = "x/(x^4 + 1)".ToEntity().Integrate("x").Simplify();
Assert.Equal("arctan(x ^ 2) / 2 + C".ToEntity().Simplify(), integral);
}

/// <summary>
/// Nothing that integrated before integrates differently. These take the other paths —
/// a substitution that does occur, partial fractions, by parts, a logarithm — so a
/// change in the candidate list would show here.
/// </summary>
[Theory]
[InlineData("x^3/(x^4 + 1)")]
[InlineData("cos(x^2) * x")]
[InlineData("sin(x) * e^x")]
[InlineData("1/(x^2 + 1)")]
[InlineData("1/(x^4 - 1)")]
[InlineData("1/(x^2 - 1)")]
[InlineData("x * ln(x)")]
[InlineData("ln(x)")]
[InlineData("x^2")]
[InlineData("sin(x) * cos(x)")]
[InlineData("e^x * x")]
public void WhatIntegratedBeforeStillDoes(string integrand)
=> DifferentiatesBack(integrand);

/// <summary>
/// And the rewrite does not make a candidate succeed that should not.
/// <c>x^2 / (x^4 + 1)</c> under <c>u = x^2</c> leaves a bare <c>x</c> behind, so it is
/// still rejected — that integral needs the denominator factored over the reals, which
/// this does not do, and it remains open on the issue.
/// </summary>
[Fact]
public void AnIntegralThisDoesNotReachIsStillDeclined()
=> Assert.Contains("integral(", "x^2/(x^4 + 1)".ToEntity().Integrate("x").Stringize());
}
}
Loading