From 8489e6c24a06199926f11b38cb504cc3f9a33635 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 30 Nov 2026 15:12:40 +0000 Subject: [PATCH] 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);