From 154a8d2f305ad1fae71383b1b7bd3e38eb67a0fa Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Sun, 6 Dec 2026 11:00:08 +0000 Subject: [PATCH] Differentiate through an argument that is constant by its spelling without a NaN The chain rule writes f'(u) u'. Where u is constant but written with the variable -- x - x, x / x, 1 - sin(x)^2 - cos(x)^2 -- u' is 0, but f'(u) can have no value: sqrt's at 0, arccos's and arcsin's at 1, the modulus's and the sign's at 0, a step's at an integer. Zero times that factor keeps the factor's condition, which is false everywhere, so sqrt(x - x) + x^2 differentiated to 2 x provided not x - x = 0, NaN after Simplify. Those rules now return zero where u' is proved zero identically: its InnerSimplified is 0 (or 0 provided a condition, kept), or it simplifies to 0 after an interval evaluation at two points has failed to show it nonzero. A u' zero only at some points keeps the term. The proof is asked only where u mentions the variable twice or holds what can flatten one occurrence (a zero, a step, a part), so a derivative through an argument that mentions the variable once allocates what it did. Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 19 +++ .../Functions/Continuous/Differentiation.cs | 126 ++++++++++++++++-- .../UnitTests/Calculus/DerivativeTest.cs | 36 +++++ 3 files changed, 171 insertions(+), 10 deletions(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index e4ccd9325..605274c1b 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -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 diff --git a/Sources/AngouriMath/Functions/Continuous/Differentiation.cs b/Sources/AngouriMath/Functions/Continuous/Differentiation.cs index 8edf6b6e2..06b8de533 100644 --- a/Sources/AngouriMath/Functions/Continuous/Differentiation.cs +++ b/Sources/AngouriMath/Functions/Continuous/Differentiation.cs @@ -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; + /// + /// The chain rule's product f'(u) u', or zero where , the + /// derivative u' of , is zero identically: see + /// . + /// + private static Entity ChainRule(Entity outer, Entity argument, Entity inner, Variable variable) + => MayBeConstantIn(argument, variable) && IdenticallyZero(inner, variable) is { } zero ? zero : outer * inner; + + /// + /// Whether , which mentions , can be a + /// constant in it: where it mentions it twice, as x - x does, or holds what can make + /// one occurrence flat -- a zero, as in x * 0, a step, as floor(x) is, or a + /// part. One occurrence through anything else varies, and asking is not paid for on the + /// common path. + /// + 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); + + /// + /// Zero where the derivative of an argument u is + /// proved zero for every value of the variable -- or zero provided its condition, + /// where it is zero wherever it has a value -- and null otherwise. + /// + /// + /// + /// Where u varies only by its spelling, x - x, x / x, + /// 1 - sin(x)^2 - cos(x)^2, its value can be the point where the outer function's + /// derivative has none: sqrt's at 0, arccos's at 1, the modulus's at 0. The + /// rule wrote f'(u) * 0, which keeps the factor's condition, false everywhere, so + /// sqrt(x - x) + x^2 differentiated to 2 x provided not x - x = 0, NaN, where + /// f(u) is a constant and the derivative is 2 x. + /// https://github.com/asc-community/AngouriMath/issues/2734 + /// + /// + /// Only an identical zero is dropped. A u' zero at a point, or on an interval, is + /// not: there f'(u) u' is a value to compute, or has none. So a value at sampled + /// points only says no, and a yes needs u' 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. + /// + /// + 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 }; + /// /// This node's own rule of differentiation. Parts are differentiated by /// , which answers zero for a constant before a rule @@ -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' @@ -513,7 +610,7 @@ partial record Arcsecantf // asec(a) = 1 / (sqrt(1 - 1 / a2)a2) * a' /// 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 @@ -521,7 +618,7 @@ partial record Arccosecantf // asec(a) = 1 / (sqrt(1 - 1 / a2)a2) * a' /// 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 @@ -547,7 +644,7 @@ partial record Arcsinf // arcsin(x)' = 1 / sqrt(1 - x^2) * x' /// 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 @@ -555,7 +652,7 @@ partial record Arccosf // arccos(x)' = -1 / sqrt(1 - x^2) * x' /// 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 @@ -723,6 +820,7 @@ partial record Signumf /// 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 @@ -748,17 +846,22 @@ partial record Absf // https://github.com/asc-community/AngouriMath/issues/1186 /// 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 @@ -802,14 +905,16 @@ partial record Floorf // has Providedf to say more with. /// 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 { /// 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 @@ -818,7 +923,8 @@ partial record Roundf // jumps where the argument is exactly a half, not where it is an integer. /// 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 diff --git a/Sources/Tests/UnitTests/Calculus/DerivativeTest.cs b/Sources/Tests/UnitTests/Calculus/DerivativeTest.cs index a40c39def..981b366a4 100644 --- a/Sources/Tests/UnitTests/Calculus/DerivativeTest.cs +++ b/Sources/Tests/UnitTests/Calculus/DerivativeTest.cs @@ -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()); + /// + /// 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 f'(u) * 0 kept the + /// factor's condition, false everywhere: sqrt(x - x) + x^2 differentiated to NaN. + /// Pinned by value at x = 7/10, checked against mpmath. + /// #2734 + /// + [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);