diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index bce7cee9a..a6df5dc2f 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -121,6 +121,29 @@ the working digits, or `MathS.Settings.PrecisionErrorZeroRange` where a caller h still that integer, so `e^(-123.456)` is 0 as it was. [#1338](https://github.com/asc-community/AngouriMath/issues/1338). +### The factorial far from zero, and a quotient by a number whose modulus is nearly whole + +The numerical factorial is Spouge's approximation, and it holds right of zero. Used left of zero it +lost its digits as the argument neared `-a`, where `a` is a tenth over the precision's digits. Past +`-a` it had none: at 30 digits `(-38.0785)!` came out `-3.1e-35`, where it is `7.03e-43`. Left of +zero it now takes the reflection formula, `x! = pi x/(sin(pi x) (-x)!)`. Its working context also +bounded the exponent where the caller's did, so an intermediate outside that range lost its digits +though the value fit. And the complex division read a divisor's modulus through `Abs()`, which +turns the downcasting on, so even with it off a modulus within its tolerance of a small rational +was that rational: `75 + 316.22776601683796i`, whose modulus is `325 - 3e-16`, divided as by 325. +The factorial's series, which runs with the downcasting off, cancels such quotients almost +entirely, which made `(316.22776601683796i)!` 24 orders of magnitude out. With the downcasting off +the division now takes the modulus as it is; with it on, the rounding is the setting's own and +stays ([#1614](https://github.com/asc-community/AngouriMath/issues/1614)). + +| Input | Was (2.5.0) | Now | +|---|---|---| +| `"(400.5)!".EvalNumerical()` | `+oo` | `1.2818906666758219960…E+870` | +| `"(316.22776601683796i)!".EvalNumerical()` | `7.23303935E-191 + 2.200942072E-190i` | `0`: the value, `-8.33E-215 - 7.33E-216i`, is below the default precision's floor | +| `"1/(75 + 316.22776601683796i)"`, downcasting off | `0.00071005917159763313609… - 0.00299387234098781500591…i` | `0.00071005917159763302214990… - 0.00299387234098781452548…i` | +| `"(-38.0785)!"` at 30 digits, downcasting off | `-3.13914586443552289958547548164E-35` | `7.03406751543900910211608330734E-43` | +| `"(-60.5)!"` at 30 digits, downcasting off | `5.86118478907722232671451280188E-81` | `2.93059239453861116335725639905E-81` | + ### A quotient of polynomials is split into coprime blocks before a root is peeled off `SolveByPartialFractions` tried `TrySplitOffRationalRoot` before `TrySplitIntoCoprimeParts`. Both diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs index ffc8c2ed2..127602fea 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs @@ -136,7 +136,18 @@ internal static Complex OpDiv(T a, T b) where T : Number => * => ans = (a + ib) * (c - id) / (c2 + d2) */ var conj = b.Conjugate; - var bAbs = b.Abs().EDecimal; + // With the downcasting off, the modulus as it is. Abs() turns the downcasting + // on to answer a Real, and so read a modulus within its tolerance of a small + // rational as that rational: 75 + 316.22776601683796i, whose modulus is + // 325 - 3e-16, was divided as if by one of 325. A relative 2e-18 is nothing to + // one quotient. It put a factorial out by 24 orders of magnitude, whose series + // of such quotients cancels its terms almost entirely. With the downcasting on, + // that reading is the setting's own, and it keeps the quotients of a divisor + // like 1 + i sqrt(3) exact. https://github.com/asc-community/AngouriMath/issues/1614 + var bAbs = MathS.Settings.DowncastingEnabled + ? b.Abs().EDecimal + : (b.RealPart.EDecimal * b.RealPart.EDecimal + b.ImaginaryPart.EDecimal * b.ImaginaryPart.EDecimal) + .SqrtByIntegerRoot(MathS.Settings.DecimalPrecisionContext); // The squared modulus of a divisor of 3 * 10^125 is 10^251 and its // reciprocal is under the context's exponent floor, so the quotient // came out zero where it was 6 * 10^-7 -- a right antiderivative's @@ -942,26 +953,41 @@ public static Complex Factorial(Complex x) if (!mathContext.Precision.CanFitInInt32()) throw new CannotEvalException($"The precision of the {nameof(mathContext)} is outside the int32 range"); + // With no imaginary part it is a real number, and its poles are the real line's. + if (x.ImaginaryPart.EDecimal.IsZero) + return x.RealPart.EDecimal.Factorial(mathContext); + var precision = mathContext.Precision.ToInt32Checked(); + var working = InternalAMExtensions.FactorialWorkingContext(precision); using var _ = MathS.Settings.DowncastingEnabled.Set(false); - using var __ = MathS.Settings.DecimalPrecisionContext.Set(mathContext.WithBigPrecision(mathContext.Precision << 1)); - // https://en.wikipedia.org/wiki/Spouge%27s_approximation - int a = mathContext.Precision.ToInt32Checked() * 13 / 10; + // Twice the digits, and no bound on the exponent, which the caller's context put on + // every intermediate: up the imaginary axis the value falls as e^(-pi |y|/2), and + // near that context's floor (280i)! lost its imaginary part and (316i)! came out 1e-190, + // where it is 8e-215. Left of zero the reflection formula, as on the real line. + // https://github.com/asc-community/AngouriMath/issues/1614 + using var __ = MathS.Settings.DecimalPrecisionContext.Set(working); + var result = x.RealPart.EDecimal.IsNegative + ? Real.Create(InternalAMExtensions.ConstantCache.Lookup(working).Pi) * x + / (Sin(Real.Create(InternalAMExtensions.ConstantCache.Lookup(working).Pi) * x) * SpougeFactorial(-x, precision)) + : SpougeFactorial(x, precision); - var constants = InternalAMExtensions.GetSpougeFactorialConstants(a); + return Complex.Create(result.RealPart.EDecimal.RoundToPrecision(mathContext), + result.ImaginaryPart.EDecimal.RoundToPrecision(mathContext)); + } - var negative = false; + /// + /// x! by Spouge's approximation, for Re x >= 0, in the working context + /// in force, before any rounding back. + /// https://en.wikipedia.org/wiki/Spouge%27s_approximation + /// + private static Complex SpougeFactorial(Complex x, int precision) + { + var a = precision * 13 / 10; + var constants = InternalAMExtensions.GetSpougeFactorialConstants(a); var factor = Complex.Create(constants[0], 0); for (int k = 1; k < a; k++) - { factor += constants[k] / (x + k); - negative = !negative; - } - - var result = Pow(x + a, x + 0.5m) * Exp(-x - a) * factor; - - return Complex.Create(result.RealPart.EDecimal.RoundToPrecision(mathContext), - result.ImaginaryPart.EDecimal.RoundToPrecision(mathContext)); + return Pow(x + a, x + 0.5m) * Exp(-x - a) * factor; } /// diff --git a/Sources/AngouriMath/Functions/InternalAMExtensions.cs b/Sources/AngouriMath/Functions/InternalAMExtensions.cs index 22671fa11..91e13219f 100644 --- a/Sources/AngouriMath/Functions/InternalAMExtensions.cs +++ b/Sources/AngouriMath/Functions/InternalAMExtensions.cs @@ -1191,27 +1191,49 @@ public static EDecimal Factorial(this EDecimal x, EContext mathContext) if (!mathContext.Precision.CanFitInInt32()) throw new WrongNumberOfArgumentsException($"The precision of the {nameof(mathContext)} is outside the int32 range"); - // https://en.wikipedia.org/wiki/Spouge%27s_approximation - var mc = mathContext.WithBigPrecision(mathContext.Precision << 1); + var precision = mathContext.Precision.ToInt32Checked(); + var mc = FactorialWorkingContext(precision); + // Spouge's approximation holds right of zero. Left of it, the reflection formula + // x! = pi x/(sin(pi x) (-x)!) asks it at -x. Used left of zero it lost its digits as x + // neared -a, and past -a had none: at 30 digits (-38.0785)! was -3.1e-35, where it is + // 7.03e-43. https://github.com/asc-community/AngouriMath/issues/1614 + if (x.IsNegative) + { + var piX = ConstantCache.Lookup(mc).Pi.Multiply(x, mc); + return piX.Divide(piX.Sin(mc).Multiply(SpougeFactorial(x.Negate(), precision, mc), mc), mc).RoundToPrecision(mathContext); + } + return SpougeFactorial(x, precision, mc).RoundToPrecision(mathContext); + } - var a = mathContext.Precision.ToInt32Checked() * 13 / 10; + /// + /// x! by Spouge's approximation with a a tenth over , + /// for Re x >= 0, before any rounding back. + /// https://en.wikipedia.org/wiki/Spouge%27s_approximation + /// + private static EDecimal SpougeFactorial(EDecimal x, int precision, EContext mc) + { + var a = precision * 13 / 10; var constants = GetSpougeFactorialConstants(a); - - var negative = false; var factor = constants[0]; for (int k = 1; k < a; k++) - { factor = factor.Add(constants[k].Divide(x.Add(k), mc)); - negative = !negative; - } - var result = x.Add(a).Pow(x.Add(0.5m), mc); result = result.Multiply(x.Negate().Subtract(a).Exp(mc)); - result = result.Multiply(factor); - - return result.RoundToPrecision(mathContext); + return result.Multiply(factor); } + /// + /// The factorial's working context: twice 's digits, and no bound on + /// the exponent. The caller's context bounded it, so an intermediate past its ceiling or below + /// its floor lost its digits though the value fit: at the default precision (400.5)! was + /// +oo, where it is 1.28e870. One per precision, so that the constants the library + /// caches per context stay few. https://github.com/asc-community/AngouriMath/issues/1614 + /// + internal static EContext FactorialWorkingContext(int precision) + => factorialWorkingContexts.GetOrAdd(precision, static precision + => EContext.ForPrecision(precision << 1).WithRounding(ERounding.HalfEven).WithUnlimitedExponents()); + [ConcurrentField] private static readonly ConcurrentDictionary factorialWorkingContexts = new(); + // GetOrAdd may run the factory more than once for one key under contention, and that is // harmless here: the constants are a pure function of `a`, so the losers are wasted work // rather than a different answer. What it cannot do is hand back another key's entry. diff --git a/Sources/Tests/UnitTests/Core/FactorialFarFromZeroTest.cs b/Sources/Tests/UnitTests/Core/FactorialFarFromZeroTest.cs new file mode 100644 index 000000000..580198dca --- /dev/null +++ b/Sources/Tests/UnitTests/Core/FactorialFarFromZeroTest.cs @@ -0,0 +1,90 @@ +// +// 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 AngouriMath.Extensions; +using PeterO.Numbers; +using Xunit; + +namespace AngouriMath.Tests.Core +{ + /// + /// The factorial far from zero, against mpmath at 120 digits. Spouge's approximation holds right + /// of zero, and was used left of it, where it lost its digits as the argument neared -a, + /// a tenth over the precision's digits, and past that had none. Its working context also kept + /// the caller's exponent range, so an intermediate outside it lost its digits though the value + /// fit. + /// #1614 + /// + [Trait("Area", "Core")] + public sealed class FactorialFarFromZeroTest + { + private static void Close(string expected, EDecimal actual, int digits) + { + var reference = EDecimal.FromString(expected); + var context = EContext.ForPrecision(digits + 10); + var error = actual.Subtract(reference, context).Abs().Divide(reference.Abs(), context); + Assert.True(error.CompareTo(EDecimal.Create(1, -digits)) < 0, $"expected {reference}, got {actual}"); + } + + private static Entity.Number.Complex Evaluate(string expression, EContext context) + { + using var _ = MathS.Settings.DowncastingEnabled.Set(false); + using var __ = MathS.Settings.DecimalPrecisionContext.Set(context); + return expression.ToEntity().EvalNumerical(); + } + + /// + /// At 30 digits (-38.0785)! was -3.1e-35, past -a = -39 in all but + /// name; at 50 digits (-60.5)! was right to 17 of its 50. + /// + [Theory] + [InlineData("(-38.0785)!", 30, "7.03406751543900910211608330733991847884857639e-43")] + [InlineData("(-60.5)!", 30, "2.93059239453861116335725639905020058758321509e-81")] + [InlineData("(-60.5)!", 50, "2.93059239453861116335725639905020058758321509e-81")] + public void LeftOfZeroAtALoweredPrecision(string expression, int precision, string expected) + => Close(expected, Evaluate(expression, new EContext(precision, ERounding.HalfUp, -100, 1000, false)).RealPart.EDecimal, precision - 5); + + /// + /// At the default precision (400.5)! was +oo: its power passed the context's + /// ceiling before the product came back under it. + /// + [Fact] + public void PastTheCeilingOfTheWorkingContext() + => Close("1.28189066667582199607925256051715548702277083e+870", Evaluate("(400.5)!", MathS.Settings.DecimalPrecisionContext).RealPart.EDecimal, 40); + + /// + /// (316.22776601683796i)! was 1e-190, where it is 8e-215. One of its + /// series' quotients divides by 75 + 316.22776601683796i, whose modulus is + /// 325 - 3e-16, and the division read that modulus as 325. + /// + [Fact] + public void WhereADivisorsModulusIsNearlyWhole() + { + var value = Evaluate("(316.22776601683796i)!", EContext.ForPrecision(100).WithUnlimitedExponents()); + Close("-8.32854615617784905610360064877990338622863321e-215", value.RealPart.EDecimal, 40); + Close("-7.33446822786649926529220121549200466400903939e-216", value.ImaginaryPart.EDecimal, 40); + } + + /// And the division itself, with the downcasting off. + [Fact] + public void ADivisorsModulusNearAWholeNumberIsNotRoundedToIt() + { + var value = Evaluate("1/(75 + 316.22776601683796i)", MathS.Settings.DecimalPrecisionContext); + Close("0.0007100591715976330221499029626337976624432319278680176295104113131192888", value.RealPart.EDecimal, 60); + Close("-0.002993872340987814525483818825494753213055396187438519990678101458851071", value.ImaginaryPart.EDecimal, 60); + } + + /// The reflection formula off the real line, which the complex factorial now takes left of zero. + [Fact] + public void LeftOfZeroOffTheRealLine() + { + var value = Evaluate("(-50.3 + 2i)!", MathS.Settings.DecimalPrecisionContext); + Close("-3.46690964930292155331561366202252533865989646e-66", value.RealPart.EDecimal, 40); + Close("5.16747446844479010758579974394398842370825775e-66", value.ImaginaryPart.EDecimal, 40); + } + } +}