From 8489e6c24a06199926f11b38cb504cc3f9a33635 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 30 Nov 2026 15:12:40 +0000 Subject: [PATCH 1/3] Keep evaluation's digits from 1e-100000 to 1e100000 (#2668) The default DecimalPrecisionContext had a hundred digits but exponents from -100 to 1000 only. An exact part below 10^-100 became 0 as a decimal and one past 10^1000 became +oo, so every digit built on it was wrong: sqrt(1/10^200 + 1/10^210) * 10^100 was 0, exp(3000) * exp(-3000) was NaN, and the exact roots Solve writes for an equation in 10^20 x evaluated to points with a residual of 1.36. The range is now -100000 to 100000, both ways, so that a number and its reciprocal are both held. With the range open, three precision limits that the flush had hidden showed, and are fixed with it: - the sine, cosine and arctangent ran in fixed point, whose guard digits are absolute, so below 10^-8 (10^-5 for the arctangent) they lost digits and at 10^-200 gave 0; they are now summed as series in floating point there; - the reduction of a sine's argument by 2 pi used pi to the working digits, so from 10^8 up it lost a digit per digit of the argument, and sin(10^500) had none right; it is now reduced with pi to as many more digits as the argument has, and an exact rational argument is written out to that many digits; - the Hermite reduction over two binomials of degree three or four was declined only because its check overflowed. Over the range, its answer to x^7 (a + b x^3)^(1/3)/(c + d x^3) is 23,030 characters, where the cube root's rules give 2,861. It is now declined for that pair, as the split by residues already declines it. Tests changed because their answers got better: the flushed gamma parts are asked for in a context ending at 1e-100, as the default did, with the default's values pinned beside them; catalannumber(2000.5), (1e600 + 1e600 i)^2 and three comparisons were +oo or stayed written, and are now their values, mpmath's. The rows still past the range moved past the new ends. Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 37 ++++++++- Sources/AngouriMath/Convenience/MathS.cs | 8 +- .../Entity/Continuous/Number/Operators.cs | 30 ++++++-- .../Integration/IndefiniteIntegralSolver.cs | 25 ++++++ .../Functions/InternalAMExtensions.cs | 76 +++++++++++++++++++ .../AComparisonOfExactNumbersIsExactTest.cs | 11 ++- ...FlushedPartOfTheGammaFunctionIsZeroTest.cs | 23 ++++++ .../Common/NumericsRegressionTest.cs | 57 ++++++++++++++ .../ACatalanNumberPastTheExponentRangeTest.cs | 6 +- .../Core/AComplexOverflowIsNotNaNTest.cs | 11 +-- 10 files changed, 265 insertions(+), 19 deletions(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 141bf3467..a3001652f 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -42,6 +42,38 @@ A not-equal written `<>` is read as `not (a = b)`, and printed that way. ## Unreleased — since 2.10.0 +### Evaluation keeps its digits from 1e-100000 to 1e100000 + +**Silent: wrong numbers become right ones.** The decimals evaluation works in had a hundred digits, but exponents only +from -100 to 1000. An exact part below `10^-100` was 0 as a decimal, and one past `10^1000` was `+oo`, so every digit +built on such a part was wrong: `sqrt(1/10^200 + 1/10^210) * 10^100` was 0, and the exact roots `Solve` writes for an +equation in `10^20 x` evaluated to points that are not roots. The exponents now run from -100000 to 100000. The sine, +cosine and arctangent of a tiny argument are summed as series in floating point, where their fixed point had no digits +left. The sine and cosine of a large argument are reduced by `2 pi` taken to as many more digits as the argument has +before its point, and an exact rational argument is written out to that many digits too. Before, `sin(10^500)` had no +right digit. A caller that sets its own `DecimalPrecisionContext` keeps that context's range. Measured on 2.10.0 and on +this branch ([#2668](https://github.com/asc-community/AngouriMath/issues/2668)). + +| `.Evaled` | Was (2.10.0) | Now | +|---|---|---| +| `sqrt(1/10^200 + 1/10^210) * 10^100` | `0` | `1.00000000004999999999875…` | +| `sqrt(10^(-300)) * 10^150` | `0` | `1` | +| `(1/10^200 + i/10^200) * 10^200` | `1` | `1 + i` | +| `2^(-1000) * sqrt(2) * 2^1000` | `0` | `1.41421356237309504880…` | +| `exp(-1000)` | `0` | `5.07595889754945676529…E-435` | +| `exp(3000)` | `+oo` | `7.64620098905470488931…E+1302` | +| `exp(3000) * exp(-3000)` | `NaN` | `1` | +| `sin(1/10^200) * 10^200`, and `arctan` | `0` | `1` | +| `sin(10^60)` | `0.83038976521934266466…8514636898040…`, wrong from the 49th digit | `…8514630714107…` | +| `sin(10^500)` | `-0.27853856742087907707…` | `0.31102693090790028047…` | +| `sin(2^1000)` | `0.29150829785727846625…` | `-0.15920170308624243824…` | +| `cos(10^5000)` | `NaN` | `-0.72745055141283323318…` | +| `gamma(316 * i)` | `0` | `3.55632285366604152450…E-217 + 1.28845172909637752912…E-217i` | +| `catalannumber(2000.5)` | `+oo` | `1.66144399474248826784…E+1199` | +| `(1e600 + 1e600 * i)^2` | `+ooi` | `2.000…E+1200i` | + +The range still ends: `exp(-240000)` is 0 and `(1 + i)^(10^6)` is `+oo`, and a comparison of two such sides stays written. + ### A number past the working digits is not taken for an exact one **Not silent: wrong answers become exact ones.** At the default hundred digits, a product past about `10^50` @@ -83,8 +115,9 @@ before v3, which decides exact comparisons exactly (#1019 §10). Two decimals th | `10^(-200) < 2 * 10^(-200)` | `False` | `True` | | `1000! * 2 < 1001!` | `False` | `True` | | `10^(590) >= 10^(590) + 10^(440)` | `True` | `False` | -| `exp(-1000.5) > exp(-3002.5)` | `False` | stays written | -| `exp(-2000) = exp(-2000.5)` | `True` | stays written | +| `exp(-1000.5) > exp(-3002.5)` | `False` | `True`, both sides within the exponents since [#2668](https://github.com/asc-community/AngouriMath/issues/2668) | +| `exp(-2000) = exp(-2000.5)` | `True` | `False`, likewise | +| `exp(-240000) = exp(-240000.5)` | `True` | stays written | | `sqrt(5)^1000 = 5^500` | `False` | stays written | | `sqrt(2) < sqrt(2) + 10^(-150)` | `False` | stays written | diff --git a/Sources/AngouriMath/Convenience/MathS.cs b/Sources/AngouriMath/Convenience/MathS.cs index f1e3e5536..c93772fa1 100644 --- a/Sources/AngouriMath/Convenience/MathS.cs +++ b/Sources/AngouriMath/Convenience/MathS.cs @@ -6776,8 +6776,14 @@ internal static EDecimal DowncastingTolerance /// /// Settings for precisions of PeterO.Numbers /// + /// + /// A hundred digits, at any magnitude from 1e-100000 to 1e100000. The exponents ended at -100 and + /// 1000, so that an exact part below 1e-100 was 0 as a decimal and every digit built on it was + /// wrong: sqrt(1/10^200 + 1/10^210) * 10^100 was 0, and exp(3000) * exp(-3000) was + /// NaN. https://github.com/asc-community/AngouriMath/issues/2668 + /// public static Setting DecimalPrecisionContext { get; } = - new(new EContext(100, ERounding.HalfUp, -100, 1000, false)); + new(new EContext(100, ERounding.HalfUp, -100000, 100000, false)); /// /// Whether functions are being read as real-valued or complex-valued. It is a diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs index 0e3345e11..ac2414330 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs @@ -953,12 +953,28 @@ private static (EDecimal Sinh, EDecimal Cosh) SinhAndCosh(EDecimal y, EContext c return (p.Subtract(q, work).Divide(2, work).RoundToPrecision(context), p.Add(q, work).Divide(2, work).RoundToPrecision(context)); } + /// + /// The argument a periodic function reduces: , the number's decimal, but for a + /// rational past 10^8 its decimal to as many more digits as it has before its point, which the + /// reduction by 2 pi takes away. In the context's digits alone 2^1000 is known to 1e202, + /// and sin(2^1000) came back 0.29 where it is -0.16. + /// https://github.com/asc-community/AngouriMath/issues/2668 + /// + private static EDecimal PeriodicArgument(Real real, EDecimal written, EContext context) + { + if (real is not Rational { ERational: var exact } || !written.IsFinite || written.CompareToTotalMagnitude(tenToTheEight) < 0) + return written; + var magnitude = written.Exponent.Add(written.Precision()).ToInt32Checked(); + return exact.ToEDecimal(EContext.ForPrecision(context.Precision.ToInt32Checked() + magnitude + 16).WithUnlimitedExponents()); + } + [ConstantField] private static readonly EDecimal tenToTheEight = EDecimal.FromString("1E+8"); + /// Calculates the exact value of sine of num public static Complex Sin(Complex num) { var context = MathS.Settings.DecimalPrecisionContext; - if (num is Real { EDecimal: var real }) - return Real.CreateAtScale(real.Sin(context), real); + if (num is Real { EDecimal: var real } asReal) + return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Sin(context), real); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 var (re, im) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); var (sinh, cosh) = SinhAndCosh(im, context); @@ -1019,8 +1035,8 @@ public static Real Abs(Complex num) public static Complex Cos(Complex num) { var context = MathS.Settings.DecimalPrecisionContext; - if (num is Real { EDecimal: var real }) - return Real.CreateAtScale(real.Cos(context), real); + if (num is Real { EDecimal: var real } asReal) + return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Cos(context), real); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 var (re, im) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); var (sinh, cosh) = SinhAndCosh(im, context); @@ -1036,8 +1052,8 @@ public static Complex Cos(Complex num) public static Complex Tan(Complex num) { var context = MathS.Settings.DecimalPrecisionContext; - if (num is Real { EDecimal: var real }) - return Real.CreateAtScale(real.Tan(context), real); + if (num is Real { EDecimal: var real } asReal) + return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Tan(context), real); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 // tan z = sin z / cos z, but to avoid unnecessary repeated trig computations, use @@ -1084,6 +1100,8 @@ public static Complex Cotan(Complex num) var (x, y) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); if (!x.IsFinite || !y.IsFinite) return Integer.One / Tan(num); + if (num is Real asReal) + x = PeriodicArgument(asReal, x, context); var (sin, cos) = (x.Sin(context), x.Cos(context)); // sin x is a residual of x as on the real line, and 0 at a pole: cot of pi to the working digits is NaN. if (y.IsZero) diff --git a/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs b/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs index ee24ac498..fa2017aab 100644 --- a/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs @@ -2558,6 +2558,7 @@ is var (multiple, leftover) // reached the same answer through them after seventeen seconds of peeling and // re-factoring; this way it is under a second. if (Mulf.LinearChildren(denominator).Any(f => f.ContainsNode(x) && f is Powf(_, Number.Integer { EInteger.Sign: > 0 } e) && e != Number.Integer.One) + && !TwoBinomialsPastTheSecondDegree(denominator, x) && IntegrateByAnsatz(null, numerator / denominator, x) is { } byHermite) return byHermite; @@ -3297,6 +3298,30 @@ private static Entity WithTheDenominatorInPowersOf(Entity value, IReadOnlyList + /// Whether has two factors, each written once or as a power, + /// that are binomials of degree three or four in . Over two such + /// binomials with symbols in them the Hermite reduction's system answers in coefficients + /// pages long -- x^7 (a + b x^3)^(1/3)/(c + d x^3), which the cube root's + /// substitution makes one over (u^3 - 1/b)^3 and c + (a d - b c) u^3, came back + /// in 23,030 characters with c^50 in them, where the rules for the cube root write + /// 2,861. The split by residues declines the same pair for the same reason. Over 1e1000 the + /// check of that answer used to overflow, which declined it by accident. + /// https://github.com/asc-community/AngouriMath/issues/2668 + /// + private static bool TwoBinomialsPastTheSecondDegree(Entity denominator, Entity.Variable x) + { + var binomials = 0; + foreach (var factor in Mulf.LinearChildren(denominator)) + { + var written = factor is Powf(var @base, Number.Integer { EInteger.Sign: > 0 }) ? @base : factor; + if (written.ContainsNode(x) && TreeAnalyzer.TryGetPolynomial(written, x, out var read) + && read.Count == 2 && read.Keys.Max() is { } degree && (degree.Equals(EInteger.FromInt32(3)) || degree.Equals(EInteger.FromInt32(4)))) + binomials++; + } + return binomials > 1; + } + /// /// N/(B_1 ... B_m) where every block B_i is a polynomial in x^n for one /// n >= 2, linear or quadratic in it, with a symbol among them: split in diff --git a/Sources/AngouriMath/Functions/InternalAMExtensions.cs b/Sources/AngouriMath/Functions/InternalAMExtensions.cs index b2f06febb..69334d4c4 100644 --- a/Sources/AngouriMath/Functions/InternalAMExtensions.cs +++ b/Sources/AngouriMath/Functions/InternalAMExtensions.cs @@ -531,7 +531,39 @@ internal static EContext WithUnboundedExponents(EContext context) /// internal static (EDecimal Sin, EDecimal Cos) SinAndCos(EDecimal x, EContext context) { + // Reduced below by a multiple of 2 pi in pi's working digits, whose error the multiple + // scales: from 10^8 on that is more than the guard digits, and sin(10^500) had none of + // its digits right. So the reduction is done first with pi to as many more digits as + // the argument has before its point. https://github.com/asc-community/AngouriMath/issues/2668 + if (x.CompareToTotalMagnitude(tenToTheEight) >= 0) + return SinAndCos(ReducedByTwoPi(x, context.Precision.ToInt32Checked() + x.Exponent.Add(x.Precision()).ToInt32Checked()), context); var working = WithGuardDigits(context, 8); + if (x.CompareToTotalMagnitude(belowEightGuardDigits) < 0) + { + // Fixed point carries the eight guard digits as absolute precision, so below + // 10^-8 a sine would come back short of the context's digits, and at 10^-200 as + // 0. The two series in floating point instead, a handful of terms each. + // https://github.com/asc-community/AngouriMath/issues/2668 + var xSquared = x.Multiply(x, working); + var smallSin = x; + var smallCos = EDecimal.One; + var sinPower = x; + var cosPower = EDecimal.One; + for (var k = 1; k < 100000; k++) + { + cosPower = cosPower.Multiply(xSquared, working).Divide(-(2 * k - 1) * (2 * k), working); + sinPower = sinPower.Multiply(xSquared, working).Divide(-(2 * k) * (2 * k + 1), working); + var nextSin = smallSin.Add(sinPower, working); + var nextCos = smallCos.Add(cosPower, working); + // Compared as numbers: a zero's terms are zeros of ever smaller exponents, which + // differ from each other as representations. + if (nextSin.CompareTo(smallSin) == 0 && nextCos.CompareTo(smallCos) == 0) + break; + smallSin = nextSin; + smallCos = nextCos; + } + return (smallSin.RoundToPrecision(context), smallCos.RoundToPrecision(context)); + } var consts = ConstantCache.Lookup(working); var bits = consts.FixedBits; var one = consts.FixedOne; @@ -596,6 +628,28 @@ internal static (EDecimal Sin, EDecimal Cos) SinAndCos(EDecimal x, EContext cont return (FromFixed(sin, consts, working).RoundToPrecision(context), FromFixed(cos, consts, working).RoundToPrecision(context)); } + /// + /// less the multiple of 2 pi nearest it, to about + /// less the digits has before its point, which + /// is 2 pi's error times the multiple. 2 pi is made once for each 256 digits a + /// thread asks for: a thousand digits of it take milliseconds, and twenty thousand a second. + /// + private static EDecimal ReducedByTwoPi(EDecimal x, int digits) + { + var bucket = (digits + 32 + 255) / 256 * 256; + var held = twoPiByDigits ??= new(); + if (!held.TryGetValue(bucket, out var entry)) + { + var wide = EContext.ForPrecision(bucket).WithUnlimitedExponents(); + entry = (wide, EDecimal.PI(wide).Multiply(2, wide)); + held[bucket] = entry; + } + // Not RemainderNear, which is NaN for a quotient of five hundred digits. + var turns = x.Divide(entry.TwoPi, entry.Context).RoundToExponent(0, ERounding.HalfEven); + return x.Subtract(turns.Multiply(entry.TwoPi, entry.Context), entry.Context); + } + [ThreadStatic] private static Dictionary? twoPiByDigits; + /// Analogy of public static EDecimal Tan(this EDecimal x, EContext context) { @@ -708,6 +762,25 @@ public static EDecimal Arctan(this EDecimal x, EContext context) var working = WithGuardDigits(context, 5); if (x.GreaterThan(EDecimal.One)) return ConstantCache.Lookup(working).HalfPi.Subtract(Arctan(EDecimal.One.Divide(x, working), working), working).RoundToPrecision(context); + if (x.CompareTo(belowFiveGuardDigits) < 0) + { + // Below 10^-5 the fixed point's absolute precision, five guard digits, would + // leave the arctangent short of the context's digits, and at 10^-200 it was 0; + // so the series in floating point, a handful of terms. + // https://github.com/asc-community/AngouriMath/issues/2668 + var xSquared = x.Multiply(x, working); + var power = x; + var smallSum = x; + for (var k = 1; k < 100000; k++) + { + power = power.Multiply(xSquared, working).Negate(); + var next = smallSum.Add(power.Divide(2 * k + 1, working), working); + if (next.CompareTo(smallSum) == 0) + break; + smallSum = next; + } + return smallSum.RoundToPrecision(context); + } // In fixed point from here. The nearest sixty-fourth is exact in fixed point // (FixedBits is at least six), so the table's entry is the arctangent of it. @@ -978,6 +1051,9 @@ private static BigInteger TwiceArtanh(BigInteger y, int bits) return sum << 1; } + [ConstantField] private static readonly EDecimal tenToTheEight = EDecimal.FromString("1E+8"); + [ConstantField] private static readonly EDecimal belowEightGuardDigits = EDecimal.FromString("1E-8"); + [ConstantField] private static readonly EDecimal belowFiveGuardDigits = EDecimal.FromString("1E-5"); [ConstantField] private static readonly EDecimal sqrt2 = EDecimal.FromString("1.4142135623730950488"); [ConstantField] private static readonly EDecimal halfSqrt2 = EDecimal.FromString("0.70710678118654752440"); diff --git a/Sources/Tests/UnitTests/Common/AComparisonOfExactNumbersIsExactTest.cs b/Sources/Tests/UnitTests/Common/AComparisonOfExactNumbersIsExactTest.cs index 78b3a2412..a8e09d439 100644 --- a/Sources/Tests/UnitTests/Common/AComparisonOfExactNumbersIsExactTest.cs +++ b/Sources/Tests/UnitTests/Common/AComparisonOfExactNumbersIsExactTest.cs @@ -34,14 +34,19 @@ public sealed class AComparisonOfExactNumbersIsExactTest [InlineData("sqrt(2) < 3/2", true)] [InlineData("exp(-300) > exp(-400)", true)] [InlineData("10^(-20) = 2 * 10^(-20)", false)] + // A side was flushed to 0 or saturated to +oo, so these stayed written, until the exponents + // reached a hundred thousand. https://github.com/asc-community/AngouriMath/issues/2668 + [InlineData("exp(-1000.5) > exp(-3002.5)", true)] + [InlineData("exp(6000) >= exp(6100)", false)] + [InlineData("exp(-2000) = exp(-2000.5)", false)] public void TheComparisonIsDecided(string comparison, bool expected) => Assert.Equal(Boolean.Create(expected), comparison.ToEntity().Evaled); /// Where the decimals cannot tell the sides apart, or made a side 0 or infinite, nothing is answered. [Theory] - [InlineData("exp(-1000.5) > exp(-3002.5)")] - [InlineData("exp(6000) >= exp(6100)")] - [InlineData("exp(-2000) = exp(-2000.5)")] + [InlineData("exp(-100000.5) > exp(-300002.5)")] + [InlineData("exp(600000) >= exp(610000)")] + [InlineData("exp(-240000) = exp(-240000.5)")] [InlineData("sqrt(2) < sqrt(2) + 10^(-150)")] [InlineData("sqrt(5)^1000 = 5^500")] public void AnUndecidedComparisonStaysWritten(string comparison) diff --git a/Sources/Tests/UnitTests/Common/AFlushedPartOfTheGammaFunctionIsZeroTest.cs b/Sources/Tests/UnitTests/Common/AFlushedPartOfTheGammaFunctionIsZeroTest.cs index 4659bb81f..801fbb3f9 100644 --- a/Sources/Tests/UnitTests/Common/AFlushedPartOfTheGammaFunctionIsZeroTest.cs +++ b/Sources/Tests/UnitTests/Common/AFlushedPartOfTheGammaFunctionIsZeroTest.cs @@ -6,6 +6,7 @@ // using AngouriMath.Extensions; +using PeterO.Numbers; using Xunit; using static AngouriMath.Entity; @@ -18,6 +19,9 @@ namespace AngouriMath.Tests.Common /// under the caller's downcasting at scale 0, the gamma function having no zero, so such a part is the /// number 0. Found while looking for more values made like the modulus; no issue was filed. /// https://github.com/asc-community/AngouriMath/issues/1944 + /// The default context's exponents reach a hundred thousand since + /// https://github.com/asc-community/AngouriMath/issues/2668, where these parts are values, so the flush is + /// asked for in a context that ends at a hundred, as the default did. /// [Trait("Area", "Common")] public sealed class AFlushedPartOfTheGammaFunctionIsZeroTest @@ -28,10 +32,29 @@ public sealed class AFlushedPartOfTheGammaFunctionIsZeroTest [InlineData("(-120.5 + i)!", "-4E-199i")] public void TheFlushedPartIsTheNumberZero(string expression, string printed) { + using var _ = MathS.Settings.DecimalPrecisionContext.Set(EndingAtAHundred); var value = Assert.IsAssignableFrom(expression.ToEntity().Evaled); Assert.Equal(printed, value.Stringize()); if (value.RealPart.EDecimal.IsZero) Assert.Equal(Number.Integer.Zero, value.RealPart); } + + /// In the default context the parts are the values, mpmath's at forty digits. + [Theory] + [InlineData("gamma(316 * i)", "3.55632285366604152450997486031256605873e-217", "1.288451729096377529120983509747604578448e-217")] + [InlineData("gamma(-150.5 + i)", "-1.163634010568670660051098838385025746287e-265", "3.697441350995165490943321390628052726267e-265")] + [InlineData("(-120.5 + i)!", "3.347981151862649670060674556532022609712e-200", "-4.448622106215105827990642710609597358892e-199")] + public void InTheDefaultContextThePartsAreTheirValues(string expression, string real, string imaginary) + { + var value = Assert.IsAssignableFrom(expression.ToEntity().Evaled); + AssertNear(EDecimal.FromString(real), value.RealPart.EDecimal); + AssertNear(EDecimal.FromString(imaginary), value.ImaginaryPart.EDecimal); + } + + private static void AssertNear(EDecimal expected, EDecimal actual) + => Assert.True(actual.Subtract(expected).Abs().CompareTo(expected.Abs().Multiply(EDecimal.FromString("1e-35"))) <= 0, + $"{actual} is not {expected}"); + + private static readonly EContext EndingAtAHundred = new(100, ERounding.HalfUp, -100, 1000, false); } } diff --git a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs index ebfbd64a2..62bdf0708 100644 --- a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs @@ -462,6 +462,63 @@ root is Entity.Number.Complex complex and not Entity.Number.Real && complex.ImaginaryPart.EDecimal.Abs().ToDouble() < 1e-15); } + // An exact expression whose parts are below 10^-100 was evaluated in a context whose least + // exponent was -100, so those parts flushed to 0 and the digits built on them were wrong: + // sqrt(1/10^200 + 1/10^210) * 10^100 was 0. The fixed-point sine and arctangent had the same + // floor at their absolute precision, and the sine's reduction by 2 pi lost a digit for each + // the argument has before its point. The true values are mpmath's at sixty digits. + // https://github.com/asc-community/AngouriMath/issues/2668 + [Theory] + [InlineData("sqrt(1/10^200 + 1/10^210) * 10^100", "1.0000000000499999999987500000000624999999960937500002734375")] + [InlineData("sqrt(10^(-300)) * 10^150", "1")] + [InlineData("2^(-1000) * sqrt(2) * 2^1000", "1.41421356237309504880168872420969807856967187537694807317667973799")] + [InlineData("exp(-1000) * 10^435", "5.07595889754945676529180947957433691930559928289283736183239")] + [InlineData("sin(1/10^200) * 10^200", "1")] + [InlineData("tan(1/10^200) * 10^200", "1")] + [InlineData("arctan(1/10^200) * 10^200", "1")] + [InlineData("arcsin(1/10^200) * 10^200", "1")] + [InlineData("exp(3000) * exp(-3000)", "1")] + // And the reduction of a large argument by 2 pi, in pi's working digits and the argument's. + [InlineData("sin(10^60)", "0.830389765219342664664061785421328756641175851463071410787033")] + [InlineData("sin(10^500)", "0.311026930907900280476371099336527312857391520496193130880434")] + [InlineData("cos(10^5000)", "-0.727450551412833233187102017089898394988591219691054476349643")] + [InlineData("sin(2^1000)", "-0.159201703086242438240048630820839033813686898777465015367511")] + public void Issue2668_AnExactExpressionBelowTheExponentFloorKeepsItsDigits(string expression, string trueValue) + { + var value = Assert.IsAssignableFrom(expression.ToEntity().EvalNumerical()); + var expected = EDecimal.FromString(trueValue); + Assert.True(value.EDecimal.Subtract(expected).Abs().CompareTo(expected.Abs().Multiply(EDecimal.FromString("1E-55"))) <= 0, + $"{expression} is {value}"); + } + + // A complex number's parts below the floor flushed too, and the imaginary part was lost: + // (1/10^200 + i/10^200) * 10^200 was 1. https://github.com/asc-community/AngouriMath/issues/2668 + [Fact] + public void Issue2668_AComplexNumberBelowTheExponentFloorKeepsBothParts() + { + var value = Assert.IsAssignableFrom("(1/10^200 + i/10^200) * 10^200".ToEntity().EvalNumerical()); + Assert.Equal(EDecimal.One, value.RealPart.EDecimal.RoundToPrecision(EContext.ForPrecision(50))); + Assert.Equal(EDecimal.One, value.ImaginaryPart.EDecimal.RoundToPrecision(EContext.ForPrecision(50))); + } + + // The exact roots Solve writes for an equation in 10^20 x evaluated to wrong digits, a residual + // of 1.36, because their parts are below 10^-100; mpmath puts the root at + // (0.393078192784 + 0.273588473883i) / 10^20. https://github.com/asc-community/AngouriMath/issues/2668 + [Fact] + public void Issue2668_AnExactRootAtTenToTheMinusTwentyEvaluatesToARoot() + { + var equation = "((-2i) + 3y) + (-2 + 3y) abs(-3y) = 0".ToEntity().Substitute("y", "10^20 x"); + var roots = Assert.IsType(equation.Solve("x")); + Assert.NotEmpty(roots); + foreach (var root in roots) + { + var scaled = Assert.IsAssignableFrom((root * "10^20").EvalNumerical()); + var residual = Assert.IsAssignableFrom( + "((-2i) + 3y) + (-2 + 3y) abs(-3y)".ToEntity().Substitute("y", scaled).EvalNumerical()); + Assert.True(residual.Abs().EDecimal.CompareTo(EDecimal.FromString("1E-80")) < 0, $"{root} leaves {residual}"); + } + } + // A rational root of an exact number is that root only where its power is the number exactly: one // within 1e-16 of it was taken, so the square root of 9 + 4/10^24 was 3, which made the quadratic // x^2 - 3x - 1/10^24 lose both its roots. The differences are worked out in mpmath at eighty digits. diff --git a/Sources/Tests/UnitTests/Convenience/ACatalanNumberPastTheExponentRangeTest.cs b/Sources/Tests/UnitTests/Convenience/ACatalanNumberPastTheExponentRangeTest.cs index 21562e0c8..0991cc1f5 100644 --- a/Sources/Tests/UnitTests/Convenience/ACatalanNumberPastTheExponentRangeTest.cs +++ b/Sources/Tests/UnitTests/Convenience/ACatalanNumberPastTheExponentRangeTest.cs @@ -30,6 +30,9 @@ public sealed class ACatalanNumberPastTheExponentRangeTest [InlineData("catalannumber(500.5)", "1.0773809195193076398539141613347340467488925064819e+297")] [InlineData("catalannumber(1600.25)", "2.462290001548975528409180780699097156132733259886e+958")] [InlineData("catalannumber(-60.3)", "-8.3875179942165737514658221112507292321206364599213e-40")] + // Past a thousand in the exponent, where the context ended until + // https://github.com/asc-community/AngouriMath/issues/2668 and this was +oo. + [InlineData("catalannumber(2000.5)", "1.66144399474248826784242667520475373551525929097900129545165e+1199")] // A quotient of factorials under the downcasting tolerance, which is not a residual. [InlineData("fallingfactorial(0.5, -100.5)", "9.4019927548161528235486105066852002441716212361456e-161")] [InlineData("risingfactorial(100.5, -60.5)", "2.1883878150169778143163818514630537992056282322519e-111")] @@ -42,8 +45,7 @@ public void IsItsValue(string input, string expected) } [Theory] - // 1.7e1199, and about 10^(6e39): past the range, where a real is +oo. - [InlineData("catalannumber(2000.5)")] + // About 10^(6e39): past the range, where a real is +oo. [InlineData("catalannumber(1e40 + 0.2)")] public void IsPositiveInfinityPastTheRange(string input) => Assert.Equal(Entity.Number.Real.PositiveInfinity, Within(input)); diff --git a/Sources/Tests/UnitTests/Core/AComplexOverflowIsNotNaNTest.cs b/Sources/Tests/UnitTests/Core/AComplexOverflowIsNotNaNTest.cs index 786bb599b..471ce5aa0 100644 --- a/Sources/Tests/UnitTests/Core/AComplexOverflowIsNotNaNTest.cs +++ b/Sources/Tests/UnitTests/Core/AComplexOverflowIsNotNaNTest.cs @@ -16,10 +16,11 @@ namespace AngouriMath.Tests.Core { /// - /// A complex number's parts are decimals in the precision context, whose exponents end at a thousand. A + /// A complex number's parts are decimals in the precision context, whose exponents end at a hundred + /// thousand (at a thousand until https://github.com/asc-community/AngouriMath/issues/2668). A /// product or a power of finite numbers a part of which passed that end had oo - oo in it and was - /// NaN, which says the value does not exist: (3 + 4 * i)^2000, (1 + i)^(10^6) and - /// (1e600 + 1e600 * i)^2 among them. Each part past the range is the infinity of its sign now, as a + /// NaN, which says the value does not exist: (1 + i)^(10^6) and (1e60000 + 1e60000 * i)^2 + /// among them. Each part past the range is the infinity of its sign now, as a /// real past it is +oo, and an exact simplification leaves the expression as written. No issue was /// filed. /// @@ -27,8 +28,8 @@ namespace AngouriMath.Tests.Core public sealed class AComplexOverflowIsNotNaNTest { [Theory] - [InlineData("(1e600 + 1e600 * i)^2")] - [InlineData("(1e600 + 1e600 * i) * (1e600 + 1e600 * i)")] + [InlineData("(1e60000 + 1e60000 * i)^2")] + [InlineData("(1e60000 + 1e60000 * i) * (1e60000 + 1e60000 * i)")] public void AProductPastTheRangeHasItsParts(string input) { var value = Within(() => input.ToEntity().Evaled, input); From d4ad38fb440c95be957d0db92e582733ef14a07f Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 30 Nov 2026 20:47:52 +0000 Subject: [PATCH 2/3] Decide past-the-range values up front, and keep the special functions' reach (#2668) Widening the exponents let finite numbers past 1e1000 reach algorithms that had only ever seen +oo there, and some of them work through the argument's digits: - e^x for a huge x was taken by PeterO's exponential, which works its way to the overflow through a power of e as large as x, and inside ExpDifference in a context with no exponent range. sinh(exp(10000)) took 38 s to be +oo, and limitcheck went from 28 s to 44.5 s. Past ln 10 times the context's ends, e^x is now +oo or 0 from x's size alone, and e^v (e^d - 1) is e^(v+d) or -e^v once d is past them. - erf, erfc, erfi, Ei, Si, Ci, Shi, Chi, the gamma function, a quotient of factorials, polygamma off the real line, and the complex paths of exp, the trigonometric functions and arcsin/arccos did not finish in 20 s at 10^5000, or lost every digit to their residual scales. sin(10^5000 + i) had no imaginary part, and arcsin(10^5000) was 0. They take a part past 10^1000 as the infinity it was, so their answers there are master's. - e to a complex power now goes through Exp, as e to a real power does: the polar form multiplied the imaginary part by ln e's hundred digits, so cosh(10^5000 i) was -0.86 where it is cos(10^5000), -0.73. - zeta past a double's range counted its terms through doubles and threw on a negative precision, which zeta(-10^900) did on master too. It is left as written past a million. Measured: limitcheck 27.7/28.0 s on master and 28.3/28.1 s here, with 2 more cases compared and the same 0 wrong; sinh(exp(10000)) 38,604 ms -> 131 ms in-process. Suite 21993 passed. Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 8 +++ .../Continuous/Number/ErrorFunctions.cs | 3 + .../Continuous/Number/ExponentialIntegrals.cs | 1 + .../Entity/Continuous/Number/Operators.cs | 57 +++++++++++++++++++ .../Entity/Continuous/Number/Polygamma.cs | 4 ++ .../Number/TrigonometricIntegrals.cs | 1 + .../Core/Entity/Continuous/Number/Zeta.cs | 7 +++ ...aluation.Continuous.Arithmetics.Classes.cs | 6 ++ .../Functions/InternalAMExtensions.cs | 26 ++++++++- .../Common/NumericsRegressionTest.cs | 32 +++++++++++ 10 files changed, 144 insertions(+), 1 deletion(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index a3001652f..59cb96e54 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -71,8 +71,16 @@ this branch ([#2668](https://github.com/asc-community/AngouriMath/issues/2668)). | `gamma(316 * i)` | `0` | `3.55632285366604152450…E-217 + 1.28845172909637752912…E-217i` | | `catalannumber(2000.5)` | `+oo` | `1.66144399474248826784…E+1199` | | `(1e600 + 1e600 * i)^2` | `+ooi` | `2.000…E+1200i` | +| `cotan(1 - 3000i)` | `i` | `3.1106026543…E-2606 + i` | +| `binomial(10^5000, 1.5)` | `0.75225277806…`, where it is about `7.5E+7499` | stays written | +| `zeta(-10^900)` | throws `ArgumentException` | stays written | The range still ends: `exp(-240000)` is 0 and `(1 + i)^(10^6)` is `+oo`, and a comparison of two such sides stays written. +An exponential past it is decided from the size of its argument, so `sinh(exp(10000))` is `+oo` at once. The special +functions (`erf`, `erfc`, `erfi`, `Ei`, `Si`, `Ci`, `Shi`, `Chi`, the gamma function, and a quotient of factorials), and +the complex paths of the exponential, the trigonometric functions and `arcsin`/`arccos`, take a part past `10^1000` as +the infinity it was before. Their algorithms do work that grows with the argument's digits, and some lose every digit +there. Their answers past `10^1000` are therefore what they were. ### A number past the working digits is not taken for an exact one diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/ErrorFunctions.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/ErrorFunctions.cs index ce7826f00..08e24f103 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/ErrorFunctions.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/ErrorFunctions.cs @@ -44,6 +44,7 @@ partial record Number /// public static Complex Erf(Complex z) { + z = WithinTheSpecialFunctionsReach(z); var context = MathS.Settings.DecimalPrecisionContext.Value; var (re, im) = (z.RealPart.EDecimal, z.ImaginaryPart.EDecimal); if (re.IsNaN() || im.IsNaN()) @@ -73,6 +74,7 @@ public static Complex Erf(Complex z) /// public static Complex Erfc(Complex z) { + z = WithinTheSpecialFunctionsReach(z); var context = MathS.Settings.DecimalPrecisionContext.Value; var (re, im) = (z.RealPart.EDecimal, z.ImaginaryPart.EDecimal); if (re.IsNaN() || im.IsNaN()) @@ -120,6 +122,7 @@ public static Complex Erfc(Complex z) /// public static Complex Erfi(Complex z) { + z = WithinTheSpecialFunctionsReach(z); // On the real line, where it is real, it is summed as a real function, so that its // imaginary part is zero and not a rounding residue; it grows without bound. if (z.ImaginaryPart.EDecimal.IsZero && z.RealPart.EDecimal is var x && !x.IsNaN()) diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs index bfd96350c..0fb44d5ed 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs @@ -48,6 +48,7 @@ partial record Number /// public static Complex Ei(Complex z) { + z = WithinTheSpecialFunctionsReach(z); var context = MathS.Settings.DecimalPrecisionContext.Value; var (re, im) = (z.RealPart.EDecimal, z.ImaginaryPart.EDecimal); if (re.IsNaN() || im.IsNaN()) diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs index ac2414330..6a60b9c14 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs @@ -556,6 +556,12 @@ public static Complex Sqrt(Complex num) /// exp(x) = e^x public static Complex Exp(Complex x) { + // Off the real line a part past the reach is the infinity it was: the cosine and the sine of an + // imaginary part past 10^50 are below the residual its size allows, and e^(2 10^5000 i) kept its real + // part alone, so that tanh(10^5000 i) had a real part of -0.89. + // https://github.com/asc-community/AngouriMath/issues/2668 + if (!x.ImaginaryPart.EDecimal.IsZero) + x = WithinTheSpecialFunctionsReach(x); var context = MathS.Settings.DecimalPrecisionContext; var expReal = x.RealPart.EDecimal.Exponential(context); var imaginary = x.ImaginaryPart.EDecimal; @@ -621,6 +627,12 @@ static Complex BinaryIntPow(Complex num, EInteger val) if (@base is Real { EDecimal: var maybeE } && power is Real { EDecimal: var realExponent } && maybeE.Equals(InternalAMExtensions.ConstantCache.Lookup(MathS.Settings.DecimalPrecisionContext).E)) return Real.CreateAtScale(realExponent.Exponential(MathS.Settings.DecimalPrecisionContext), EDecimal.Zero); + // And to a complex power, for the same reason: the polar form multiplies the power's imaginary part + // by ln e's hundred digits, so cosh(10^5000 i) came back -0.86 where it is cos(10^5000), -0.73. + // https://github.com/asc-community/AngouriMath/issues/2668 + if (@base is Real { EDecimal: var maybeEOfComplex } && power is not Real + && maybeEOfComplex.Equals(InternalAMExtensions.ConstantCache.Lookup(MathS.Settings.DecimalPrecisionContext).E)) + return Exp(power); // TODO: make it more detailed (e. g. +oo ^ +oo = +oo) // A whole power, whether written as an integer or, for a base off the // positive axis, as a decimal with nothing after the point -- which is how `2` @@ -969,12 +981,33 @@ private static EDecimal PeriodicArgument(Real real, EDecimal written, EContext c } [ConstantField] private static readonly EDecimal tenToTheEight = EDecimal.FromString("1E+8"); + /// + /// with a part past 10^1000 read as the infinity of its sign, for a special + /// function whose algorithm does work growing with the digits its argument has before the point. That is + /// where the context's exponents ended until https://github.com/asc-community/AngouriMath/issues/2668, + /// so such a part was an infinity already and the function answers as it did; read as a number, + /// erf(10^5000) and gamma(exp(10000)) ran past twenty seconds. + /// + internal static Complex WithinTheSpecialFunctionsReach(Complex z) + { + var (re, im) = (z.RealPart.EDecimal, z.ImaginaryPart.EDecimal); + var (pastRe, pastIm) = (PastTheReach(re), PastTheReach(im)); + if (!pastRe && !pastIm) + return z; + return Complex.Create(pastRe ? (re.IsNegative ? EDecimal.NegativeInfinity : EDecimal.PositiveInfinity) : re, + pastIm ? (im.IsNegative ? EDecimal.NegativeInfinity : EDecimal.PositiveInfinity) : im); + static bool PastTheReach(EDecimal part) => part.IsFinite && part.CompareToTotalMagnitude(specialFunctionsReach) > 0; + } + [ConstantField] private static readonly EDecimal specialFunctionsReach = EDecimal.FromString("1E+1000"); + /// Calculates the exact value of sine of num public static Complex Sin(Complex num) { var context = MathS.Settings.DecimalPrecisionContext; if (num is Real { EDecimal: var real } asReal) return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Sin(context), real); + // Off the real line a part past the reach is the infinity it was, as for Exp. + num = WithinTheSpecialFunctionsReach(num); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 var (re, im) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); var (sinh, cosh) = SinhAndCosh(im, context); @@ -1037,6 +1070,8 @@ public static Complex Cos(Complex num) var context = MathS.Settings.DecimalPrecisionContext; if (num is Real { EDecimal: var real } asReal) return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Cos(context), real); + // Off the real line a part past the reach is the infinity it was, as for Exp. + num = WithinTheSpecialFunctionsReach(num); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 var (re, im) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); var (sinh, cosh) = SinhAndCosh(im, context); @@ -1054,6 +1089,8 @@ public static Complex Tan(Complex num) var context = MathS.Settings.DecimalPrecisionContext; if (num is Real { EDecimal: var real } asReal) return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Tan(context), real); + // Off the real line a part past the reach is the infinity it was, as for Exp. + num = WithinTheSpecialFunctionsReach(num); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 // tan z = sin z / cos z, but to avoid unnecessary repeated trig computations, use @@ -1102,6 +1139,14 @@ public static Complex Cotan(Complex num) return Integer.One / Tan(num); if (num is Real asReal) x = PeriodicArgument(asReal, x, context); + else + { + // Off the real line a part past the reach is the infinity it was, as for Exp. + num = WithinTheSpecialFunctionsReach(num); + (x, y) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); + if (!x.IsFinite || !y.IsFinite) + return Integer.One / Tan(num); + } var (sin, cos) = (x.Sin(context), x.Cos(context)); // sin x is a residual of x as on the real line, and 0 at a pole: cot of pi to the working digits is NaN. if (y.IsZero) @@ -1178,6 +1223,12 @@ internal static Complex ExpDifference(Complex v, Complex d) return Integer.Zero; var context = MathS.Settings.DecimalPrecisionContext.Value; var (x, y) = (d.RealPart.EDecimal, d.ImaginaryPart.EDecimal); + // Past the exponents e^d is the whole of e^d - 1, or nothing beside the 1, to every working digit; + // and taken in the working context, which has no exponent range, it was worked out through a power + // of e as large as d: sinh(exp(10000)) took 38 seconds to be +oo. + // https://github.com/asc-community/AngouriMath/issues/2668 + if (InternalAMExtensions.PastTheExponents(x, context) is { } past) + return past.IsZero ? -Exp(v) : Exp(v + d); var extra = 10 + DigitsBelowOne(x, y); var work = Working(context, extra); Complex power, lower, product; @@ -1219,6 +1270,10 @@ private static int DigitsBelowOne(EDecimal x, EDecimal y) /// private static Complex ArcSinOrCos(Complex num, EContext context, bool cosine) { + // beta is a difference of two moduli of the argument's size, known to the working digits of that size; + // past the reach that leaves none of it, and arcsin(10^5000) was 0. The infinity it was answers as before. + // https://github.com/asc-community/AngouriMath/issues/2668 + num = WithinTheSpecialFunctionsReach(num); var (x, y) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); var work = Working(context, 10 + 2 * DigitsBelowOne(x, y)); var (beta, v, alpha) = ArcSinCosInner(num, work); @@ -1307,6 +1362,8 @@ public static Complex Arctan(Complex num) /// public static Complex Factorial(Complex x) { + if (x is not Integer { EInteger.Sign: >= 0 }) + x = WithinTheSpecialFunctionsReach(x); var mathContext = MathS.Settings.DecimalPrecisionContext.Value; switch (x) { diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/Polygamma.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/Polygamma.cs index 212e26777..a33407cd5 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/Polygamma.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/Polygamma.cs @@ -44,6 +44,10 @@ partial record Number /// public static Complex Polygamma(EInteger order, Complex z) { + // Off the real line only: on it a large argument is quick and its value, 1/x and its powers, is + // within the exponents. https://github.com/asc-community/AngouriMath/issues/2668 + if (!z.ImaginaryPart.EDecimal.IsZero) + z = WithinTheSpecialFunctionsReach(z); var context = MathS.Settings.DecimalPrecisionContext.Value; var (re, im) = (z.RealPart.EDecimal, z.ImaginaryPart.EDecimal); if (re.IsNaN() || im.IsNaN() || order.Sign < 0 || !order.CanFitInInt32()) diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs index e5c8362a3..a6171523b 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs @@ -60,6 +60,7 @@ partial record Number private static Complex TrigonometricIntegral(Complex z, bool hyperbolic, bool odd) { + z = WithinTheSpecialFunctionsReach(z); var context = MathS.Settings.DecimalPrecisionContext.Value; var (re, im) = (z.RealPart.EDecimal, z.ImaginaryPart.EDecimal); if (re.IsNaN() || im.IsNaN()) diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/Zeta.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/Zeta.cs index 6933dadbc..0f1d153dd 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/Zeta.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/Zeta.cs @@ -38,6 +38,8 @@ partial record Number /// /// https://github.com/asc-community/AngouriMath/issues/2182 /// + [ConstantField] private static readonly EDecimal beyondTheSummation = EDecimal.FromString("1E+6"); + internal static Complex? HurwitzZeta(Complex s, Complex a) { var context = MathS.Settings.DecimalPrecisionContext.Value; @@ -47,6 +49,11 @@ partial record Number return Real.NaN; if (!sr.IsFinite || !si.IsFinite || !ar.IsFinite || !ai.IsFinite) return null; + // Past a million the summation's terms are more than it takes, and past a double's range the counts + // of them, read through doubles, overflowed into a negative precision and threw: zeta(-10^900). + // https://github.com/asc-community/AngouriMath/issues/2668 + if (sr.CompareToTotalMagnitude(beyondTheSummation) > 0 || si.CompareToTotalMagnitude(beyondTheSummation) > 0) + return null; if (si.IsZero && sr.CompareTo(EDecimal.One) == 0) return Real.NaN; if (ai.IsZero && ar.Sign <= 0 && ar.IsInteger()) diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs index 51117d640..f170f6360 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs @@ -889,6 +889,12 @@ private static class FactorialPowers /// internal static Complex? QuotientOfFactorials(Complex[] over, Complex[] under) { + // A factorial past the special functions' reach is worked through its digits with no bound on the + // exponent, and did not return; it was +oo there before, and the node was left as written. + // https://github.com/asc-community/AngouriMath/issues/2668 + foreach (var x in over.Concat(under)) + if (!ReferenceEquals(Number.WithinTheSpecialFunctionsReach(x), x)) + return null; var context = MathS.Settings.DecimalPrecisionContext.Value; var unbounded = InternalAMExtensions.WithUnboundedExponents(context); if (over.All(static x => x is Real) && under.All(static x => x is Real)) diff --git a/Sources/AngouriMath/Functions/InternalAMExtensions.cs b/Sources/AngouriMath/Functions/InternalAMExtensions.cs index 69334d4c4..2dcf9257d 100644 --- a/Sources/AngouriMath/Functions/InternalAMExtensions.cs +++ b/Sources/AngouriMath/Functions/InternalAMExtensions.cs @@ -1127,7 +1127,7 @@ public static EDecimal NaturalLogarithm(this EDecimal x, EContext context) public static EDecimal Exponential(this EDecimal x, EContext context) { if (!x.IsFinite || x.Abs().CompareTo(EDecimal.FromInt32(1000)) > 0) - return x.Exp(context); + return PastTheExponents(x, context) ?? x.Exp(context); if (x.IsZero) return EDecimal.One; // Twelve guard digits: the ten squarings each double the error, three digits, @@ -1169,6 +1169,30 @@ public static EDecimal Exponential(this EDecimal x, EContext context) .RoundToPrecision(context); } + /// + /// +oo or 0 where e^x is past 's exponents, decided from + /// x against ln 10 times the largest and the least exponent, and null where it is + /// not. PeterO's exponential works its way to the overflow through a power of e as large + /// as the argument: sinh(exp(10000)), whose argument is 8.8e4342, took 38 seconds to be + /// +oo once the exponents reached a hundred thousand. + /// https://github.com/asc-community/AngouriMath/issues/2668 + /// + internal static EDecimal? PastTheExponents(EDecimal x, EContext context) + { + if (!x.IsFinite || !context.HasExponentRange) + return null; + // Two exponents beyond each end, and the subnormals' digits below the least, so that + // nothing within the range is decided here. + var over = EDecimal.FromEInteger(context.EMax.Add(2)).Multiply(lnTenAbove); + if (x.CompareTo(over) > 0) + return EDecimal.PositiveInfinity; + var under = EDecimal.FromEInteger(context.EMin.Negate().Add(context.Precision).Add(2)).Multiply(lnTenAbove).Negate(); + if (x.CompareTo(under) < 0) + return EDecimal.Zero; + return null; + } + [ConstantField] private static readonly EDecimal lnTenAbove = EDecimal.FromString("2.3026"); + /// Analogy of public static EDecimal Sinh(this EDecimal x, EContext context) { diff --git a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs index 62bdf0708..41e96a0cf 100644 --- a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs @@ -519,6 +519,38 @@ public void Issue2668_AnExactRootAtTenToTheMinusTwentyEvaluatesToARoot() } } + // Past the exponents an exponential is +oo or 0 from its argument's size alone: worked through, sinh of + // exp(10000), 8.8e4342, took 38 seconds to be +oo once the exponents reached a hundred thousand, and + // erf(10^5000) did not finish in twenty. + // https://github.com/asc-community/AngouriMath/issues/2668 + [Theory] + [InlineData("sinh(exp(10000))", "+oo")] + [InlineData("sinh(-10^5000)", "-oo")] + [InlineData("cosh(exp(10000))", "+oo")] + [InlineData("tanh(exp(10000))", "1")] + [InlineData("tanh(-10^5000)", "-1")] + // And a special function past 10^1000 is the value at the infinity it was there, not worked through its digits. + [InlineData("erf(10^5000)", "1")] + [InlineData("erfc(-10^5000)", "2")] + [InlineData("Ei(-10^5000)", "0")] + [InlineData("Shi(exp(10000))", "+oo")] + [InlineData("gamma(exp(10000))", "+oo")] + public void Issue2668_AFunctionPastTheExponentsTerminates(string expression, string expected) + { + Entity? value = null; + var task = System.Threading.Tasks.Task.Run(() => value = expression.ToEntity().Evaled); + Assert.True(task.Wait(System.TimeSpan.FromSeconds(30)), $"{expression} did not finish in thirty seconds"); + Assert.Equal(expected.ToEntity().Evaled, value); + } + + // zeta past a double's range counted its terms through doubles, overflowed into a negative precision and + // threw; it is left as written, as it is from a million. https://github.com/asc-community/AngouriMath/issues/2668 + [Theory] + [InlineData("zeta(-10^900)")] + [InlineData("zeta(-exp(3000))")] + public void Issue2668_AZetaPastTheSummationIsLeftAsWritten(string expression) + => Assert.IsType(expression.ToEntity().Evaled); + // A rational root of an exact number is that root only where its power is the number exactly: one // within 1e-16 of it was taken, so the square root of 9 + 4/10^24 was 3, which made the quadratic // x^2 - 3x - 1/10^24 lose both its roots. The differences are worked out in mpmath at eighty digits. From 0198f13e3fc0214553f9dd415000eb170897e174 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 30 Nov 2026 23:18:32 +0000 Subject: [PATCH 3/3] Give no value for a periodic function of a decimal past its digits (#2668) A decimal argument is known to the working digits, so reducing it by 2 pi leaves precision - k of them for an argument near 10^k. Past 10^(precision - 16) the sine and cosine were mostly noise: cos(exp(300)) was 0.23 where it is -0.98. Widening the exponents let values past 10^1000 reach the same reduction, so cos(exp(10000)), which was NaN, became 0.31 where it is 0.92. SinAndCos is now NaN for a decimal past that bound. An exact rational is written out to the digits its reduction needs and goes through SinAndCosOfAnExactArgument at any size, so cos(10^150 + 1/3) and cos(10^150/3) are right. Si of such a decimal is +-pi/2, and Ei far up the imaginary axis is +-i pi, where the oscillating part is below the working digits. Suite 22012 passed; limitcheck 27.4/27.9 s on master, 27.7/28.1 s here. Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 21 +++++++++ .../Continuous/Number/ExponentialIntegrals.cs | 11 +++++ .../Entity/Continuous/Number/Operators.cs | 29 ++++++++---- .../Number/TrigonometricIntegrals.cs | 7 +++ .../Functions/InternalAMExtensions.cs | 23 +++++++++- .../Common/NumericsRegressionTest.cs | 45 +++++++++++++++++++ 6 files changed, 127 insertions(+), 9 deletions(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 59cb96e54..b81aecd81 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -82,6 +82,27 @@ the complex paths of the exponential, the trigonometric functions and `arcsin`/` the infinity it was before. Their algorithms do work that grows with the argument's digits, and some lose every digit there. Their answers past `10^1000` are therefore what they were. +**Not silent: a periodic function of a decimal past its digits is `NaN`.** A decimal argument is known only to the +working digits. Reduced by `2 pi`, an argument of size `10^k` keeps `precision - k` of them, so the sine, cosine, +tangent and cotangent of a decimal past `10^(precision - 16)` was a number whose digits were all, or nearly all, noise. +The same holds on the complex paths through them: `e` to an imaginary power, and a power by the polar form. Such a +value is now `NaN`, which says the evaluation has none to give. An exact rational argument is reduced exactly, at any +size. `Si` of such a decimal is `±pi/2`, and `Ei` far up the imaginary axis is `±i pi`, where the oscillating part is +below the working digits. `Ci` of such a decimal is `NaN`. So is `sin(x)^2 + cos(x)^2` evaluated numerically at such +an `x`, where it was `1` because the noise was consistent. Measured on 2.10.0 and on this branch; the true values are +mpmath's at 4500 digits. + +| `.Evaled` | Was (2.10.0) | Now | True | +|---|---|---|---| +| `cos(exp(300))` | `0.23214…` | `NaN` | `-0.98403…` | +| `sin(exp(300))` | `0.97268…` | `NaN` | `0.17801…` | +| `cos(sqrt(2)*10^200)` | `-0.76230…` | `NaN` | `0.018225…` | +| `cos(pi*10^200)` | `-0.99338…` | `NaN` | `1.0` | +| `tan(exp(500))` | `-0.55478…` | `NaN` | `0.52510…` | +| `e^(i*exp(300))` | `0.23214…` | `NaN` | `-0.98403… + 0.17801…i` | +| `Ci(exp(300))` | `0` | `NaN` | below `1e-130`, sign unknown | +| `cos(10^150/3)` | `-0.44819…` | `0.80881903093981837173…` | `0.80881903093981837173…` | + ### A number past the working digits is not taken for an exact one **Not silent: wrong answers become exact ones.** At the default hundred digits, a product past about `10^50` diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs index 0fb44d5ed..5d9d42056 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs @@ -57,6 +57,17 @@ public static Complex Ei(Complex z) return im.IsZero && re.IsInfinity() ? (re.IsNegative ? Integer.Zero : Real.PositiveInfinity) : Real.NaN; if (re.IsZero && im.IsZero) return Real.NegativeInfinity; + // Off the real line at an imaginary part from 10^(precision - 16), the cosine and the sine of which have + // no digits to give, Ei is i pi sgn(Im z) beside e^z/z; where that is below the working digits it is the + // value, Ei(10^130 i) among them, and otherwise there is none. + // https://github.com/asc-community/AngouriMath/issues/2668 + if (!im.IsZero && im.CompareToTotalMagnitude(tenToTheEight) >= 0 + && im.Exponent.Add(im.Precision()).CompareTo(context.Precision.Subtract(16)) > 0) + { + var digitsOfTheRest = re.ToDouble() / Math.Log(10) - ((double)im.Exponent.Add(im.Precision()).ToInt64Checked() - 1); + if (digitsOfTheRest < -(context.Precision.ToInt32Checked() + 2)) + return Complex.Create(EDecimal.Zero, im.IsNegative ? EDecimal.PI(context).Negate() : EDecimal.PI(context)); + } var ei = Ei(re, im, context, extraDigits: 0); // A part is a residual only against what was added to make it, not against 1: Ei(-130) is about // -2.7 * 10^(-59). https://github.com/asc-community/AngouriMath/issues/1944 diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs index 6a60b9c14..706984ace 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs @@ -972,12 +972,21 @@ private static (EDecimal Sinh, EDecimal Cosh) SinhAndCosh(EDecimal y, EContext c /// and sin(2^1000) came back 0.29 where it is -0.16. /// https://github.com/asc-community/AngouriMath/issues/2668 /// - private static EDecimal PeriodicArgument(Real real, EDecimal written, EContext context) + private static (EDecimal Value, bool Exact) PeriodicArgument(Real real, EDecimal written, EContext context) { if (real is not Rational { ERational: var exact } || !written.IsFinite || written.CompareToTotalMagnitude(tenToTheEight) < 0) - return written; + return (written, false); var magnitude = written.Exponent.Add(written.Precision()).ToInt32Checked(); - return exact.ToEDecimal(EContext.ForPrecision(context.Precision.ToInt32Checked() + magnitude + 16).WithUnlimitedExponents()); + return (exact.ToEDecimal(EContext.ForPrecision(context.Precision.ToInt32Checked() + magnitude + 16).WithUnlimitedExponents()), true); + } + + /// The sine and the cosine of a real, an exact rational one reduced exactly. + private static (EDecimal Sin, EDecimal Cos) SinAndCosOfAReal(Real real, EDecimal written, EContext context) + { + if (!written.IsFinite) + return (EDecimal.NaN, EDecimal.NaN); + var (value, exact) = PeriodicArgument(real, written, context); + return exact ? InternalAMExtensions.SinAndCosOfAnExactArgument(value, context) : InternalAMExtensions.SinAndCos(value, context); } [ConstantField] private static readonly EDecimal tenToTheEight = EDecimal.FromString("1E+8"); @@ -1005,7 +1014,7 @@ public static Complex Sin(Complex num) { var context = MathS.Settings.DecimalPrecisionContext; if (num is Real { EDecimal: var real } asReal) - return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Sin(context), real); + return Real.CreateAtScale(SinAndCosOfAReal(asReal, real, context).Sin, real); // Off the real line a part past the reach is the infinity it was, as for Exp. num = WithinTheSpecialFunctionsReach(num); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 @@ -1069,7 +1078,7 @@ public static Complex Cos(Complex num) { var context = MathS.Settings.DecimalPrecisionContext; if (num is Real { EDecimal: var real } asReal) - return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Cos(context), real); + return Real.CreateAtScale(SinAndCosOfAReal(asReal, real, context).Cos, real); // Off the real line a part past the reach is the infinity it was, as for Exp. num = WithinTheSpecialFunctionsReach(num); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 @@ -1088,7 +1097,10 @@ public static Complex Tan(Complex num) { var context = MathS.Settings.DecimalPrecisionContext; if (num is Real { EDecimal: var real } asReal) - return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Tan(context), real); + { + var (sinOfReal, cosOfReal) = SinAndCosOfAReal(asReal, real, context); + return Real.CreateAtScale(cosOfReal.IsZero ? EDecimal.NaN : sinOfReal.Divide(cosOfReal, context), real); + } // Off the real line a part past the reach is the infinity it was, as for Exp. num = WithinTheSpecialFunctionsReach(num); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 @@ -1137,8 +1149,9 @@ public static Complex Cotan(Complex num) var (x, y) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); if (!x.IsFinite || !y.IsFinite) return Integer.One / Tan(num); + (EDecimal Sin, EDecimal Cos)? ofAReal = null; if (num is Real asReal) - x = PeriodicArgument(asReal, x, context); + ofAReal = SinAndCosOfAReal(asReal, x, context); else { // Off the real line a part past the reach is the infinity it was, as for Exp. @@ -1147,7 +1160,7 @@ public static Complex Cotan(Complex num) if (!x.IsFinite || !y.IsFinite) return Integer.One / Tan(num); } - var (sin, cos) = (x.Sin(context), x.Cos(context)); + var (sin, cos) = ofAReal ?? InternalAMExtensions.SinAndCos(x, context); // sin x is a residual of x as on the real line, and 0 at a pole: cot of pi to the working digits is NaN. if (y.IsZero) return Real.CreateAtScale(sin, x).IsZero ? Integer.One / Tan(num) diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs index a6171523b..8a6dbee68 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs @@ -80,6 +80,13 @@ private static Complex TrigonometricIntegral(Complex z, bool hyperbolic, bool od } if (re.IsZero && im.IsZero) return odd ? Integer.Zero : Real.NegativeInfinity; + // For a decimal on the real line from 10^(precision - 16), where a sine or a cosine of a decimal is NaN for want of + // digits, Si is +-pi/2 beside an oscillation below 1/|x|, short of its last sixteen digits at most; + // Ci is that oscillation alone, whose sign is not known, and has no value to give. + // https://github.com/asc-community/AngouriMath/issues/2668 + if (!hyperbolic && z is not Rational && im.IsZero && re.CompareToTotalMagnitude(tenToTheEight) >= 0 + && re.Exponent.Add(re.Precision()).CompareTo(context.Precision.Subtract(16)) > 0) + return odd ? Real.Create(EDecimal.PI(context).Divide(re.IsNegative ? -2 : 2, context)) : Real.NaN; var (valueRe, valueIm, reScale, imScale) = TrigonometricIntegral(re, im, hyperbolic, odd, context); // On the axes, what is known exactly is given so: Si and Shi are real on the real line // and imaginary on the imaginary axis; Ci and Chi are real on the positive real axis, i pi diff --git a/Sources/AngouriMath/Functions/InternalAMExtensions.cs b/Sources/AngouriMath/Functions/InternalAMExtensions.cs index 2dcf9257d..281e544e6 100644 --- a/Sources/AngouriMath/Functions/InternalAMExtensions.cs +++ b/Sources/AngouriMath/Functions/InternalAMExtensions.cs @@ -530,13 +530,34 @@ internal static EContext WithUnboundedExponents(EContext context) /// /// internal static (EDecimal Sin, EDecimal Cos) SinAndCos(EDecimal x, EContext context) + { + // A decimal argument is known to the context's digits, so its error is |x| 10^(-precision), + // and reduced by 2 pi that is what is left: from 10^(precision - 16) on, fewer than sixteen + // digits of the sine are right, and past 10^precision none are. cos(exp(300)), 1.9e130, + // was 0.23 where it is -0.98. It has no value to give, and is NaN; an exact argument is + // written out to the digits it needs and reduced by SinAndCosOfAnExactArgument. + // https://github.com/asc-community/AngouriMath/issues/2668 + if (x.CompareToTotalMagnitude(tenToTheEight) >= 0 + && x.Exponent.Add(x.Precision()).CompareTo(context.Precision.Subtract(DigitsAReductionKeeps)) > 0) + return (EDecimal.NaN, EDecimal.NaN); + return SinAndCosOfAnExactArgument(x, context); + } + + /// The fewest digits a reduction by 2 pi is let to leave a sine or a cosine of a decimal. + private const int DigitsAReductionKeeps = 16; + + /// + /// of an that is exactly the number it is written as, at + /// whatever magnitude: an exact rational written out to the digits its reduction needs. + /// + internal static (EDecimal Sin, EDecimal Cos) SinAndCosOfAnExactArgument(EDecimal x, EContext context) { // Reduced below by a multiple of 2 pi in pi's working digits, whose error the multiple // scales: from 10^8 on that is more than the guard digits, and sin(10^500) had none of // its digits right. So the reduction is done first with pi to as many more digits as // the argument has before its point. https://github.com/asc-community/AngouriMath/issues/2668 if (x.CompareToTotalMagnitude(tenToTheEight) >= 0) - return SinAndCos(ReducedByTwoPi(x, context.Precision.ToInt32Checked() + x.Exponent.Add(x.Precision()).ToInt32Checked()), context); + return SinAndCosOfAnExactArgument(ReducedByTwoPi(x, context.Precision.ToInt32Checked() + x.Exponent.Add(x.Precision()).ToInt32Checked()), context); var working = WithGuardDigits(context, 8); if (x.CompareToTotalMagnitude(belowEightGuardDigits) < 0) { diff --git a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs index 41e96a0cf..b0b887ea3 100644 --- a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs @@ -551,6 +551,51 @@ public void Issue2668_AFunctionPastTheExponentsTerminates(string expression, str public void Issue2668_AZetaPastTheSummationIsLeftAsWritten(string expression) => Assert.IsType(expression.ToEntity().Evaled); + // A decimal argument is known to the working digits, and past 10^(precision - 16) its reduction by 2 pi leaves + // fewer than sixteen of them: cos(exp(300)) was 0.23 where it is -0.98, and cos(exp(10000)), +oo before + // the exponents were widened, was 0.31 where it is 0.92. Such a value has none to give. + // https://github.com/asc-community/AngouriMath/issues/2668 + [Theory] + [InlineData("cos(sinh(10000))")] + [InlineData("cos(exp(10000))")] + [InlineData("cos(exp(2000))")] + [InlineData("cos(exp(300))")] + [InlineData("cos(exp(250))")] + [InlineData("sin(exp(300))")] + [InlineData("cos(sinh(300))")] + [InlineData("cos(sqrt(2)*10^200)")] + [InlineData("cos(pi*10^200)")] + [InlineData("tan(exp(500))")] + [InlineData("cotan(exp(300))")] + [InlineData("sin(exp(300) + i)")] + [InlineData("e^(i*exp(300))")] + [InlineData("(-1)^(exp(300))")] + public void Issue2668_APeriodicFunctionOfADecimalPastItsDigitsHasNoValue(string expression) + => Assert.Equal(MathS.NaN, expression.ToEntity().Evaled); + + // An exact argument is reduced exactly, at any size; and a function whose oscillating part is below its digits + // keeps the rest. The values are mpmath's. https://github.com/asc-community/AngouriMath/issues/2668 + [Theory] + [InlineData("cos(10^150 + 1/3)", "0.0181629167167074281157879688213")] + [InlineData("cos(10^150/3)", "0.80881903093981837173")] + [InlineData("sin(exp(190))", "-0.909399059783367503856902439782")] + [InlineData("Si(exp(300))", "1.5707963267948966192313216916397514420985846996875529")] + public void Issue2668_APeriodicFunctionKeepsTheDigitsItHas(string expression, string trueValue) + { + var value = Assert.IsAssignableFrom(expression.ToEntity().Evaled); + Assert.True(value.EDecimal.Subtract(EDecimal.FromString(trueValue)).Abs().CompareTo(EDecimal.FromString("1E-10")) <= 0, + $"{expression} is {value}"); + } + + [Fact] + public void Issue2668_TheExponentialIntegralFarUpTheImaginaryAxisIsIPi() + { + var value = Assert.IsAssignableFrom("Ei(i*exp(300))".ToEntity().Evaled); + Assert.True(value.RealPart.EDecimal.IsZero, $"Ei(i exp(300)) is {value}"); + Assert.True(value.ImaginaryPart.EDecimal.Subtract(EDecimal.FromString("3.14159265358979323846")).Abs().CompareTo(EDecimal.FromString("1E-10")) <= 0, + $"Ei(i exp(300)) is {value}"); + } + // A rational root of an exact number is that root only where its power is the number exactly: one // within 1e-16 of it was taken, so the square root of 9 + 4/10^24 was 3, which made the quadratic // x^2 - 3x - 1/10^24 lose both its roots. The differences are worked out in mpmath at eighty digits.