Skip to content
Open
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
19 changes: 19 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,25 @@ one point, or else `Simplify` proving it zero. A singular matrix answers as `[[1
| `"[[sin(x)^2, 1], [1 - cos(x)^2, 1]]^(-1)".Simplify()` | `NaN` | `1 / [[sin(x) ^ 2, 1], [sin(x) ^ 2, 1]]` |
| `"[[e^x, e^(2x)], [2, e^x]]^(-1)".Simplify()` | its inverse | unchanged |

### A derivative through an argument that is constant by its spelling is not NaN

**Silent: a NaN derivative now has its value.** The chain rule writes `f'(u) u'`. Where `u` is constant but
written with the variable, as `x - x`, `x / x` or `1 - sin(x)^2 - cos(x)^2` are, `u'` is 0, but `f'(u)` can have
no value: `sqrt`'s at 0, `arccos`'s at 1, the modulus's and the sign's at 0. Zero times that factor kept its
condition, which is false everywhere, so the whole derivative was NaN. Where `u'` is proved zero, the term is now
zero. A `u'` that is zero only at some points keeps the term. Measured on master (2a7247653) and on this branch
([#2734](https://github.com/asc-community/AngouriMath/issues/2734)).

| `.Differentiate("x").Simplify()` | Was (master) | Now |
|---|---|---|
| `sqrt(x - x) + x^2` | `NaN` | `2 * x` |
| `abs(x - x) + x` | `NaN` | `1` |
| `arccos(x / x) + x` | `NaN` | `1 provided not x = 0` |
| `sqrt(1 - sin(x)^2 - cos(x)^2) + x^2` | `NaN` | `2 * x` |
| `sgn(x - x) + x`, `floor(x - x) + x` | `NaN` | `1` |
| `sqrt(floor(x)) + x` | `1 provided not floor(x) = 0 and not x in ZZ` | `1 provided not x in ZZ` |
| `sqrt(x * floor(x)) + x` | `1 + floor(x) * (x * floor(x)) ^ (-1/2) / 2 provided not x in ZZ` | unchanged |

### Ei, Ci, Chi and li have limits at their logarithmic singularity

Unevaluated limits become values. `Ei(u)`, `Ci(u)` and `Chi(u)` are `eulergamma` plus the logarithm of `u` plus what
Expand Down
126 changes: 116 additions & 10 deletions Sources/AngouriMath/Functions/Continuous/Differentiation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,96 @@ internal Entity DerivativeOver(Variable variable)
private static bool SaysMoreThanAValue(Entity node)
=> node is Set or Matrix or Providedf or Piecewise || node.IsNaN;

/// <summary>
/// The chain rule's product <c>f'(u) u'</c>, or zero where <paramref name="inner"/>, the
/// derivative <c>u'</c> of <paramref name="argument"/>, is zero identically: see
/// <see cref="IdenticallyZero(Entity, Variable)"/>.
/// </summary>
private static Entity ChainRule(Entity outer, Entity argument, Entity inner, Variable variable)
=> MayBeConstantIn(argument, variable) && IdenticallyZero(inner, variable) is { } zero ? zero : outer * inner;

/// <summary>
/// Whether <paramref name="argument"/>, which mentions <paramref name="variable"/>, can be a
/// constant in it: where it mentions it twice, as <c>x - x</c> does, or holds what can make
/// one occurrence flat -- a zero, as in <c>x * 0</c>, a step, as <c>floor(x)</c> is, or a
/// part. One occurrence through anything else varies, and asking is not paid for on the
/// common path.
/// </summary>
private static bool MayBeConstantIn(Entity argument, Variable variable)
=> argument.CountNode(variable) > 1 || argument.AnyNode(MayBeFlat);

private static bool MayBeFlat(Entity node)
=> node is Number.Complex { IsZero: true } or Floorf or Ceilf or Roundf or Signumf or Imf or Ref or Argf or Modf
|| SaysMoreThanAValue(node);

/// <summary>
/// Zero where the derivative <paramref name="derivative"/> of an argument <c>u</c> is
/// proved zero for every value of the variable -- or zero <c>provided</c> its condition,
/// where it is zero wherever it has a value -- and null otherwise.
/// </summary>
/// <remarks>
/// <para>
/// Where <c>u</c> varies only by its spelling, <c>x - x</c>, <c>x / x</c>,
/// <c>1 - sin(x)^2 - cos(x)^2</c>, its value can be the point where the outer function's
/// derivative has none: <c>sqrt</c>'s at 0, <c>arccos</c>'s at 1, the modulus's at 0. The
/// rule wrote <c>f'(u) * 0</c>, which keeps the factor's condition, false everywhere, so
/// <c>sqrt(x - x) + x^2</c> differentiated to <c>2 x provided not x - x = 0</c>, NaN, where
/// <c>f(u)</c> is a constant and the derivative is <c>2 x</c>.
/// https://github.com/asc-community/AngouriMath/issues/2734
/// </para>
/// <para>
/// Only an identical zero is dropped. A <c>u'</c> zero at a point, or on an interval, is
/// not: there <c>f'(u) u'</c> is a value to compute, or has none. So a value at sampled
/// points only says no, and a yes needs <c>u'</c> to simplify to zero. The value is an
/// interval in doubles, which is cheap and still a proof when it excludes zero; the decimal
/// evaluation is asked only where the interval cannot read a node. Asked only by the rules
/// whose outer derivative has no value at a point where the function has one.
/// </para>
/// </remarks>
private static Entity? IdenticallyZero(Entity derivative, Variable variable)
{
var inner = derivative.InnerSimplified;
if (ZeroWhereDefined(inner) is { } zero)
return zero;
if (inner is Number || inner.AnyNode(SaysMoreThanAValue))
return null;
var vars = inner.Vars.ToList();
if (vars.Count == 0)
return null;
for (var point = 0; point < samplePins.Length; point++)
{
var pins = samplePins[point];
var pinned = inner;
var index = 0;
foreach (var symbol in vars)
if (symbol != variable)
pinned = pinned.Substitute(symbol, pins[++index % pins.Length]);
var interval = Numerics.IntervalEvaluation.Over(pinned, variable,
Numerics.Interval.Exactly(variablePins[point]));
if (interval is { } enclosure)
{
if (enclosure.Re.Mignitude > 0 || enclosure.Im.Mignitude > 0)
return null;
}
else if (pinned.Substitute(variable, pins[0]).Evaled is Complex { IsNaN: false } value && !value.IsZero)
return null;
}
return ZeroWhereDefined(inner.Simplify());

static Entity? ZeroWhereDefined(Entity e)
=> e == Integer.Zero ? Integer.Zero
: e is Providedf { Expression: var expression } && expression == Integer.Zero ? e
: null;
}

// The first of each is the variable's, also as the double the interval is read at.
[ConstantField] private static readonly Rational[][] samplePins =
{
new[] { Rational.Create(137, 100), Rational.Create(61, 100), Rational.Create(223, 100) },
new[] { Rational.Create(-83, 100), Rational.Create(191, 100), Rational.Create(113, 100) },
};
[ConstantField] private static readonly double[] variablePins = { 1.37, -0.83 };

/// <summary>
/// This node's own rule of differentiation. Parts are differentiated by
/// <see cref="DerivativeOver(Variable)"/>, which answers zero for a constant before a rule
Expand Down Expand Up @@ -320,8 +410,15 @@ partial record Powf
// The exponent's value where it is exact, and the exponent as written where it is not:
// pi, sqrt(2) and ln(2) evaluate to decimals, and x^pi differentiated to
// 3.14159... * x^2.14159..., which nothing reads as pi again.
//
// Below a whole exponent the factor has no value where the base is zero, so a base
// whose derivative is zero identically contributes zero rather than that factor. A
// written NaN exponent stays NaN.
// https://github.com/asc-community/AngouriMath/issues/2734
private Entity ByThePowerRule(Entity exponent, Variable variable)
=> exponent * Base.Pow((exponent - 1).InnerSimplified) * Base.DerivativeOver(variable);
=> exponent is Integer || exponent.IsNaN
? exponent * Base.Pow((exponent - 1).InnerSimplified) * Base.DerivativeOver(variable)
: ChainRule(exponent * Base.Pow((exponent - 1).InnerSimplified), Base, Base.DerivativeOver(variable), variable);

// (a ^ b)' = e ^ (ln(a) * b) * (a' * b / a + ln(a) * b')
// (a ^ const)' = const * a ^ (const - 1) * a'
Expand Down Expand Up @@ -513,15 +610,15 @@ partial record Arcsecantf
// asec(a) = 1 / (sqrt(1 - 1 / a2)a2) * a'
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable)
=> 1 / (MathS.Sqrt(1 - 1 / Argument.Pow(2)) * Argument.Pow(2)) * Argument.Differentiate(variable);
=> ChainRule(1 / (MathS.Sqrt(1 - 1 / Argument.Pow(2)) * Argument.Pow(2)), Argument, Argument.Differentiate(variable), variable);
}

partial record Arccosecantf
{
// asec(a) = 1 / (sqrt(1 - 1 / a2)a2) * a'
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable)
=> -1 / (MathS.Sqrt(1 - 1 / Argument.Pow(2)) * Argument.Pow(2)) * Argument.Differentiate(variable);
=> ChainRule(-1 / (MathS.Sqrt(1 - 1 / Argument.Pow(2)) * Argument.Pow(2)), Argument, Argument.Differentiate(variable), variable);
}

partial record Cotanf
Expand All @@ -547,15 +644,15 @@ partial record Arcsinf
// arcsin(x)' = 1 / sqrt(1 - x^2) * x'
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable) =>
1 / MathS.Sqrt(1 - MathS.Sqr(Argument)) * Argument.DerivativeOver(variable);
ChainRule(1 / MathS.Sqrt(1 - MathS.Sqr(Argument)), Argument, Argument.DerivativeOver(variable), variable);
}

partial record Arccosf
{
// arccos(x)' = -1 / sqrt(1 - x^2) * x'
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable) =>
-1 / MathS.Sqrt(1 - MathS.Sqr(Argument)) * Argument.DerivativeOver(variable);
ChainRule(-1 / MathS.Sqrt(1 - MathS.Sqr(Argument)), Argument, Argument.DerivativeOver(variable), variable);
}

partial record Arctanf
Expand Down Expand Up @@ -723,6 +820,7 @@ partial record Signumf
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable)
=> IsConstantIn(variable) ? Integer.Zero
: MayBeConstantIn(Argument, variable) && IdenticallyZero(Argument.DerivativeOver(variable), variable) is { } zero ? zero
: TreeAnalyzer.IsRealValued(Argument, variable)
? Integer.Zero.Provided(!Argument.EqualTo(Integer.Zero))
: TreeAnalyzer.WhereRealValued(Argument, variable) is { } real
Expand All @@ -748,17 +846,22 @@ partial record Absf
// https://github.com/asc-community/AngouriMath/issues/1186
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable)
=> IsConstantIn(variable) ? Integer.Zero
{
if (IsConstantIn(variable))
return Integer.Zero;
var inner = Argument.DerivativeOver(variable);
return MayBeConstantIn(Argument, variable) && IdenticallyZero(inner, variable) is { } zero ? zero
: TreeAnalyzer.TryTakeNumericModulusOut(Argument, out var withoutThePhase)
? withoutThePhase.DerivativeOver(variable)
: TreeAnalyzer.IsRealValued(Argument, variable)
? MathS.Signum(Argument).Provided(!Argument.EqualTo(Integer.Zero)) * Argument.DerivativeOver(variable)
? MathS.Signum(Argument).Provided(!Argument.EqualTo(Integer.Zero)) * inner
: TreeAnalyzer.WhereRealValued(Argument, variable) is { } real
? MathS.Piecewise(
(MathS.Signum(Argument).Provided(!Argument.EqualTo(Integer.Zero))
* TreeAnalyzer.Assuming(real, () => Argument.DerivativeOver(variable)), real),
(MathS.Derivative(this, variable), Boolean.True))
: MathS.Derivative(this, variable);
}
}

partial record Maxf
Expand Down Expand Up @@ -802,14 +905,16 @@ partial record Floorf
// has Providedf to say more with.
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable)
=> IsConstantIn(variable) ? Integer.Zero : Integer.Zero.Provided(!Argument.In(MathS.Sets.Z));
=> IsConstantIn(variable) ? Integer.Zero
: (MayBeConstantIn(Argument, variable) ? IdenticallyZero(Argument.DerivativeOver(variable), variable) : null) ?? Integer.Zero.Provided(!Argument.In(MathS.Sets.Z));
}

partial record Ceilf
{
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable)
=> IsConstantIn(variable) ? Integer.Zero : Integer.Zero.Provided(!Argument.In(MathS.Sets.Z));
=> IsConstantIn(variable) ? Integer.Zero
: (MayBeConstantIn(Argument, variable) ? IdenticallyZero(Argument.DerivativeOver(variable), variable) : null) ?? Integer.Zero.Provided(!Argument.In(MathS.Sets.Z));
}

partial record Roundf
Expand All @@ -818,7 +923,8 @@ partial record Roundf
// jumps where the argument is exactly a half, not where it is an integer.
/// <inheritdoc/>
protected override Entity InnerDifferentiate(Variable variable)
=> IsConstantIn(variable) ? Integer.Zero : Integer.Zero.Provided(!(Argument - Rational.Create(1, 2)).In(MathS.Sets.Z));
=> IsConstantIn(variable) ? Integer.Zero
: (MayBeConstantIn(Argument, variable) ? IdenticallyZero(Argument.DerivativeOver(variable), variable) : null) ?? Integer.Zero.Provided(!(Argument - Rational.Create(1, 2)).In(MathS.Sets.Z));
}

partial record Providedf
Expand Down
36 changes: 36 additions & 0 deletions Sources/Tests/UnitTests/Calculus/DerivativeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,42 @@ public void AConstantDifferentiatesToZeroWithNoCondition(string exprRaw, string
public void AConstantThatSaysMoreThanAValueKeepsIt(string exprRaw, string expected)
=> Assert.Equal(expected.ToEntity().Simplify(), exprRaw.ToEntity().Differentiate(x).Simplify());

/// <summary>
/// An argument that varies only by its spelling is a constant, and where its value is a
/// point at which the outer derivative has none, the chain rule's <c>f'(u) * 0</c> kept the
/// factor's condition, false everywhere: <c>sqrt(x - x) + x^2</c> differentiated to NaN.
/// Pinned by value at <c>x = 7/10</c>, checked against mpmath.
/// <a href="https://github.com/asc-community/AngouriMath/issues/2734">#2734</a>
/// </summary>
[Theory]
[InlineData("sqrt(x - x) + x^2", "7/5")]
[InlineData("sqrt(x * 0) + x", "1")]
[InlineData("abs(x - x) + x", "1")]
[InlineData("arccos(x / x) + x", "1")]
[InlineData("arcsin(x / x) * x", "pi / 2")]
[InlineData("sqrt(1 - sin(x)^2 - cos(x)^2) + x^2", "7/5")]
[InlineData("sqrt(x) * sqrt(x - x) + x", "1")]
[InlineData("(x - x)^(1/3) + x", "1")]
[InlineData("sgn(x - x) + x", "1")]
[InlineData("floor(x - x) + x", "1")]
[InlineData("sqrt(floor(x)) + x", "1")]
[InlineData("arcsec(x / x) + x", "1")]
// and an argument that varies keeps the factor: its derivative is zero at a point at most
[InlineData("arccos(x^2 - x^2 + x)", "-1 / sqrt(51/100)")]
[InlineData("sqrt(sin(x)^2 + cos(x)^2 + x)", "1 / (2 sqrt(17/10))")]
[InlineData("sqrt((x - 7/10)^2)", "NaN")]
public void Issue2734_AnArgumentConstantByItsSpellingDifferentiatesThroughTheChainRule(string exprRaw, string expected)
{
var derivative = exprRaw.ToEntity().Differentiate(x).Substitute(x, "7/10".ToEntity()).Evaled;
var want = expected.ToEntity().Evaled;
if (want.IsNaN)
Assert.True(derivative.IsNaN, $"{exprRaw} differentiated to {derivative} at 7/10, where it has no derivative");
else
Assert.True((derivative - want).Evaled is Number.Complex difference
&& ((Number.Real)difference.Abs()).EDecimal.ToDouble() < 1e-30,
$"{exprRaw} differentiated to {derivative} at 7/10, where it is {want}");
}

[Fact] public void AWrittenNaNStaysNaN()
{
Assert.True((MathS.Sqr(x) + MathS.NaN).Differentiate(x).Evaled.IsNaN);
Expand Down
Loading