diff --git a/Sources/.editorconfig b/Sources/.editorconfig index 7604ded7f..8235ea3c1 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -1099,3 +1099,18 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [Tests/UnitTests/Common/DotAndCrossNodesTest.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[AngouriMath/Core/Entity/Continuous/Number/MachineNumbers.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[Tests/UnitTests/Core/NumberCreationAsOf270.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[Tests/UnitTests/Core/AMachineNumberIsMadeAsBeforeTest.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[Tests/UnitTests/Core/ARealMadeWithoutDowncastingTest.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[Tests/UnitTests/Core/ANumberEvaluatesToItselfTest.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n diff --git a/Sources/AngouriMath/Convenience/MathS.cs b/Sources/AngouriMath/Convenience/MathS.cs index ad2de932b..37453f767 100644 --- a/Sources/AngouriMath/Convenience/MathS.cs +++ b/Sources/AngouriMath/Convenience/MathS.cs @@ -4795,7 +4795,7 @@ public static class Numbers /// /// public static Complex Create(NumericsComplex value) => - Complex.FromMachineNumbers(EDecimal.FromDouble(value.Real), EDecimal.FromDouble(value.Imaginary)); + Complex.FromMachineNumbers(value.Real, value.Imaginary); /// Creates an instance of from a /// A value of type (signed 64-bit integer) @@ -5128,7 +5128,7 @@ public static Rational CreateRational(EInteger numerator, EInteger denominator) /// EDecimal i9 = ((Entity.Number.Real)FromString("1 + 5").EvalNumerical()).EDecimal; /// /// - public static Real Create(double value) => Real.FromMachineNumber(EDecimal.FromDouble(value)); + public static Real Create(double value) => Real.FromMachineNumber(EDecimal.FromDouble(value), value); /// /// Creates an instance of from two s diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Complex.Definition.cs b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Complex.Definition.cs index b0d9b6c8f..0cc7b5933 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Complex.Definition.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Complex.Definition.cs @@ -107,22 +107,36 @@ internal static Complex CreateAtScales(EDecimal real, EDecimal imaginary, EDecim /// A number from a pair of s, each part rounded as /// rounds it. /// - internal static Complex FromMachineNumbers(EDecimal real, EDecimal imaginary) => Create(real, imaginary, EDecimal.One, EDecimal.One, fromMachineNumbers: true); + internal static Complex FromMachineNumbers(EDecimal real, EDecimal imaginary) => FromMachineNumbers(real, imaginary, double.NaN, double.NaN); - private static Complex Create(EDecimal real, EDecimal imaginary, EDecimal realScale, EDecimal imaginaryScale, bool fromMachineNumbers) + /// + /// of a pair of s. + /// + internal static Complex FromMachineNumbers(double real, double imaginary) + => FromMachineNumbers(EDecimal.FromDouble(real), EDecimal.FromDouble(imaginary), real, imaginary); + + /// + /// , each part's exact value also given as a + /// , or , for . + /// + internal static Complex FromMachineNumbers(EDecimal real, EDecimal imaginary, double realMachine, double imaginaryMachine) + => Create(real, imaginary, EDecimal.One, EDecimal.One, fromMachineNumbers: true, realMachine, imaginaryMachine); + + private static Complex Create(EDecimal real, EDecimal imaginary, EDecimal realScale, EDecimal imaginaryScale, bool fromMachineNumbers, + double realMachine = double.NaN, double imaginaryMachine = double.NaN) { if (!MathS.Settings.DowncastingEnabled) return new Complex(real, imaginary); - Real Part(EDecimal part, EDecimal scale) => fromMachineNumbers ? Real.FromMachineNumber(part) : Real.CreateAtScale(part, scale); + Real Part(EDecimal part, EDecimal scale, double machine) => fromMachineNumbers ? Real.FromMachineNumber(part, machine) : Real.CreateAtScale(part, scale); if (imaginary.IsZero) - return Part(real, realScale); + return Part(real, realScale, realMachine); if (real.IsNaN() || imaginary.IsNaN()) return Real.NaN; if (imaginary.IsFinite && !imaginaryScale.IsZero && imaginary.Abs().LessThan( ReferenceEquals(imaginaryScale, EDecimal.One) ? MathS.Settings.DowncastingTolerance : MathS.Settings.DowncastingTolerance.Multiply(imaginaryScale.Abs()))) - return Part(real, realScale); + return Part(real, realScale, realMachine); else - return new Complex(Part(real, realScale), Part(imaginary, imaginaryScale)); + return new Complex(Part(real, realScale, realMachine), Part(imaginary, imaginaryScale, imaginaryMachine)); } /// @@ -328,7 +342,7 @@ public static implicit operator Complex(EDecimal value) /// as the value that literal actually holds and not as one tenth. /// public static implicit operator Complex(float value) - => FromMachineNumbers(EDecimal.FromSingle(value), EDecimal.Zero); + => FromMachineNumbers(EDecimal.FromSingle(value), EDecimal.Zero, value, 0); /// /// The value as a with no imaginary part, read as the @@ -336,7 +350,7 @@ public static implicit operator Complex(float value) /// written as. /// public static implicit operator Complex(double value) - => FromMachineNumbers(EDecimal.FromDouble(value), EDecimal.Zero); + => FromMachineNumbers(EDecimal.FromDouble(value), EDecimal.Zero, value, 0); /// /// The value as a with no imaginary part. A @@ -351,7 +365,7 @@ public static implicit operator Complex(decimal value) /// parts and their precision. /// public static implicit operator Complex(System.Numerics.Complex value) => - FromMachineNumbers(EDecimal.FromDouble(value.Real), EDecimal.FromDouble(value.Imaginary)); + FromMachineNumbers(value.Real, value.Imaginary); /// The pair read as real and imaginary parts. public static implicit operator Complex((int re, int im) v) => Create(v.re, v.im); diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Number.Definition.cs b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Number.Definition.cs index adab9d7b3..8e080c267 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Number.Definition.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Number.Definition.cs @@ -89,13 +89,13 @@ public abstract partial record Number : ContinuousNode /// The value as a , read as the binary it /// is — so 0.1f becomes the value that literal holds, not one tenth. /// - public static implicit operator Number(float value) => Real.FromMachineNumber(EDecimal.FromSingle(value)); + public static implicit operator Number(float value) => Real.FromMachineNumber(EDecimal.FromSingle(value), value); /// /// The value as a , read as the binary it /// is rather than as the decimal it was written as. /// - public static implicit operator Number(double value) => Real.FromMachineNumber(EDecimal.FromDouble(value)); + public static implicit operator Number(double value) => Real.FromMachineNumber(EDecimal.FromDouble(value), value); /// /// The value as a . A is decimal @@ -108,7 +108,7 @@ public abstract partial record Number : ContinuousNode /// parts and their precision. /// public static implicit operator Number(System.Numerics.Complex value) - => Complex.FromMachineNumbers(EDecimal.FromDouble(value.Real), EDecimal.FromDouble(value.Imaginary)); + => Complex.FromMachineNumbers(value.Real, value.Imaginary); /// The big integer as an , exactly and at any size. /// /// Read as the two's-complement bytes it is, which is what diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Real.Definition.cs b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Real.Definition.cs index b3d371c8b..dded264c4 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Real.Definition.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Real.Definition.cs @@ -74,6 +74,30 @@ private protected Real() : base(null, null) { } /// public static Real Create(EDecimal value) => Create(value, fromMachineNumber: false, EDecimal.One); + /// + /// A holding exactly , never rounded onto an + /// or a , whatever + /// says: what answers + /// with the downcasting off, without opening a scope to turn it off. + /// + /// + /// + /// using System; + /// using AngouriMath; + /// using PeterO.Numbers; + /// + /// var half = EDecimal.FromString("0.5"); + /// Console.WriteLine(Entity.Number.Real.Create(half).GetType().Name); + /// Console.WriteLine(Entity.Number.Real.CreateWithoutDowncasting(half).GetType().Name); + /// + /// Prints + /// + /// Rational + /// Real + /// + /// + public static Real CreateWithoutDowncasting(EDecimal value) => new Real(value); + /// /// A value an arithmetic operation produced, which is a residual of cancellation, and zero, only below /// half the working digits of , the size of the terms that cancelled; @@ -327,13 +351,13 @@ internal static bool TryParse(string s, /// The value as a , read as the binary /// it is — so 0.1f becomes the value that literal holds, not one tenth. /// - public static implicit operator Real(float value) => FromMachineNumber(EDecimal.FromSingle(value)); + public static implicit operator Real(float value) => FromMachineNumber(EDecimal.FromSingle(value), value); /// /// The value as a , read as the binary /// it is rather than as the decimal it was written as. /// - public static implicit operator Real(double value) => FromMachineNumber(EDecimal.FromDouble(value)); + public static implicit operator Real(double value) => FromMachineNumber(EDecimal.FromDouble(value), value); /// /// The value as a . A is decimal diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/MachineNumbers.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/MachineNumbers.cs new file mode 100644 index 000000000..5ce42fe77 --- /dev/null +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/MachineNumbers.cs @@ -0,0 +1,265 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using AngouriMath.Core; +using PeterO.Numbers; + +namespace AngouriMath +{ + partial record Entity + { + partial record Number + { + partial record Real + { + /// + /// of , whose exact value is the + /// -- a , or a + /// widened to one, which is exact; where there is no such double. A value that + /// is provably no small rational, which is almost every double, is a without + /// the downcasting's search; every other value goes through it as before. + /// + /// + /// The search reads the decimal's mantissa, more than half of the bytes and the time a double took to + /// become a number; the double already has the value exactly, as a ratio of two machine integers. + /// + internal static Real FromMachineNumber(EDecimal value, double machine) + => MathS.Settings.DowncastingEnabled && IsProvablyNoSmallRational(machine) + ? new Real(value) + : FromMachineNumber(value); + + /// + /// Whether , from a machine number, provably answers the + /// it was given for : neither its rounding onto an integer nor its + /// continued-fraction search can return anything else. is no claim at all. + /// + /// + /// + /// What the downcasting can return. Write t for + /// , B for + /// , P for the working precision's + /// digits and u = 10^(1 - P). Other than the itself it returns either an integer + /// within of x -- excluded below by measuring + /// x's distance to the nearest integer, with a factor of two to spare -- or a ratio p/q, + /// |p|, q <= B, from . That runs the continued fraction + /// of |x|: y_0 = |x|, a_i = floor(y_i), r_i = y_i - a_i exactly, + /// y_(i+1) = 1/r_i rounded to the working precision, so that y_(i+1) = (1/r_i)(1 + theta) + /// with |theta| <= u (to places, an error under 10^(-P) on a quotient over 1; to digits, an ulp); + /// refuses a level with a_i > B; and stops at the level n where + /// r_n < a_n t (1 + u), at most - 1 levels + /// down, returning R = [a_0; a_1, ..., a_n]. + /// + /// + /// How far such an answer is from x. Let rho_i = [a_i; ..., a_n], v_i = 1/r_(i-1) and + /// e_i = |y_i - rho_i|. Then e_n = r_n < a_n t (1 + u), and + /// e_(i-1) = |1/v_i - 1/rho_i| <= (e_i + u v_i) / (v_i rho_i). Every rho_i and every + /// y_i past the first is at least 1, so e_(i-1) <= e_i (1 + u) + u and every + /// e_i <= E = (B t (1 + u) + N u)(1 + u)^N for N >= n; hence + /// v_i >= c rho_i with c = (1 - E)/(1 + u). Since the product of the rho_i is + /// q, unrolling gives |x - R| <= K (a_n t (1 + u) + N u q^2) / q^2, K = c^(-N). + /// Within the gate below -- P >= 30, B <= 10^9, B t <= 10^(-3), + /// N = 100 -- E < 1.001e-3 and K < 1.12; 1.2 is used. + /// + /// + /// Which ratios those can be. The same bound with a_n <= B and q <= B is under + /// 1/(2 q^2), so by Legendre's theorem R is a convergent p_k/q_k of |x| + /// itself. The levels the search took are one of R's two expansions, so n <= k + 1 and + /// a_n is a_k, 1, or a_(k-1) + 1. And |x| - p_k/q_k is + /// 1/(q_k^2 (x_(k+1) + q_(k-1)/q_k)) exactly, x_(k+1) the complete quotient. So the + /// search can return the convergent only if + /// x_(k+1) + q_(k-1)/q_k >= 1/(K (A t (1 + u) + N u q_k^2)), + /// A = min(B, max(a_k, a_(k-1) + 1)) -- a partial quotient after it near 1/(A t), a hundred + /// million at the defaults, where a double that is no small rational has its next quotient near its own + /// size. A double is m / 2^k, so its continued fraction is Euclid's algorithm on two machine + /// integers, run here exactly; every convergent within B is tested, with another factor of two + /// for the rounding of the doubles the test is made in, and one the search can return -- or a + /// fraction the double equals -- sends the value to the search. + /// + /// + /// The gate. The bound needs the context to round as it is assumed to: digits in decimal, no + /// traps, a rounding mode, and exponents where every quotient (at most 10^max(324, P)) and every + /// tolerance (at least t) is normal. Any other setting is left to the search. + /// + /// + internal static bool IsProvablyNoSmallRational(double x) + { + if (double.IsNaN(x) || double.IsInfinity(x) || x == 0) + return false; + var gate = MachineNumberGate.Current(); + if (!gate.Applies) + return false; + var magnitude = Math.Abs(x); + // Past 2^52 every double is an integer. + if (magnitude >= 4503599627370496.0) + return false; + // Exact: a double below 2^52 less its floor. + var fractional = magnitude - Math.Floor(magnitude); + if (fractional == 0 || Math.Min(fractional, 1 - fractional) <= 2 * gate.IntegerTolerance) + return false; + var bound = gate.Bound; + // The double as m / 2^k, m odd. + var bits = BitConverter.DoubleToInt64Bits(magnitude); + var biasedExponent = (int)(bits >> 52); + var m = (ulong)bits & 0xFFFFFFFFFFFFFUL; + if (biasedExponent == 0) + biasedExponent = 1; + else + m |= 1UL << 52; + var k = 1075 - biasedExponent; + while ((m & 1) == 0) + { + m >>= 1; + k--; + } + if (k <= 0) + return false; + + // The convergents p_j/q_j, the partial quotients a_j and a_(j-1), and the remainders whose ratio + // hi/lo is the complete quotient x_(j+1). + ulong p, q, pPrevious, qPrevious, a, aPrevious, hi, lo; + if (magnitude >= 1) + { + var denominator = 1UL << k; + a = m >> k; + (p, q, pPrevious, qPrevious, aPrevious) = (a, 1, 1, 0, 0); + (hi, lo) = (denominator, m & (denominator - 1)); + } + else if (k <= 63) + { + // a_0 = 0, whose convergent 0/1 the search never returns: it has no level that stops at a + // partial quotient of 0, and the integer 0 was excluded above. + (p, q, pPrevious, qPrevious, a, aPrevious) = (0, 1, 1, 0, 0, 0); + (hi, lo) = (1UL << k, m); + } + else + { + // q_1 = a_1 = floor(1/|x|) is past the bound, and so is every later denominator. + if (magnitude * (4 * (bound + 1.0)) <= 1) + return true; + // Else |x| > 2^(-32) and k <= 85: the first step of Euclid's algorithm on (2^k, m) by hand, + // 2^k mod m by doubling, and a_1 = (2^k - r)/m, under 2^32, from 1/|x| within 2^(-19). + var remainder = (1UL << 63) % m; + for (var i = 63; i < k; i++) + { + remainder <<= 1; + if (remainder >= m) + remainder -= m; + } + var first = (ulong)Math.Round(1 / magnitude - (double)remainder / m); + if (unchecked(first * m + remainder) != 0) + return false; + if (first > bound) + return true; + (p, q, pPrevious, qPrevious, a, aPrevious) = (1, first, 0, 1, first, 0); + (hi, lo) = (m, remainder); + } + + while (true) + { + // Numerators and denominators only grow from here. + if (p > bound || q > bound) + return true; + // |x| is p/q itself. + if (lo == 0) + return false; + if (p != 0) + { + var lastQuotient = Math.Min(bound, Math.Max((double)a, aPrevious + 1.0)); + var completeQuotient = (double)hi / lo + (double)qPrevious / q; + if (2 * completeQuotient * (gate.ScaledTolerance * lastQuotient + gate.ScaledRounding * ((double)q * q)) >= 1) + return false; + } + var next = hi / lo; + // q_(j+1) >= a_(j+1) > B. + if (next > bound) + return true; + (pPrevious, p) = (p, next * p + pPrevious); + (qPrevious, q) = (q, next * q + qPrevious); + (aPrevious, a) = (a, next); + (hi, lo) = (lo, hi % lo); + } + } + + /// + /// The settings reads, as doubles, with whether its bound holds + /// under them; kept for the setting values it was made from, which are compared by reference and + /// replaced whole, so that a reader never sees half of one. + /// + private sealed class MachineNumberGate + { + private readonly EContext context; + private readonly EDecimal tolerance; + private readonly EInteger maxValue; + private readonly int iterCount; + private readonly bool toleranceOverridden; + + internal readonly bool Applies; + /// B. + internal readonly ulong Bound; + /// . + internal readonly double IntegerTolerance; + /// K t (1 + u), rounded up. + internal readonly double ScaledTolerance; + /// K N u. + internal readonly double ScaledRounding; + + [ConcurrentField] private static MachineNumberGate? last; + + private MachineNumberGate(EContext context, EDecimal tolerance, EInteger maxValue, int iterCount, bool toleranceOverridden) + { + (this.context, this.tolerance, this.maxValue, this.iterCount, this.toleranceOverridden) + = (context, tolerance, maxValue, iterCount, toleranceOverridden); + IntegerTolerance = MathS.Settings.DowncastingToleranceAsDouble; + const double k = 1.2; + const int levels = 100; + if (iterCount > levels + || context.IsSimplified || context.IsPrecisionInBits || context.Traps != 0 + || context.Rounding == ERounding.None + || !context.HasMaxPrecision || !context.Precision.CanFitInInt32() + || !tolerance.IsFinite || tolerance.Sign <= 0 + || maxValue.Sign <= 0 || maxValue.CompareTo(EInteger.FromInt32(1_000_000_000)) > 0 + || !(IntegerTolerance > 0)) + return; + var digits = context.Precision.ToInt32Unchecked(); + var t = tolerance.ToDouble(); + Bound = (ulong)maxValue.ToInt64Unchecked(); + if (digits < 30 || !(t > 0) || double.IsInfinity(t) || Bound * t > 1e-3) + return; + if (context.HasExponentRange + && (!context.AdjustExponent + || context.EMin.CompareTo(EInteger.FromInt32((int)Math.Floor(Math.Log10(t)) - 1)) > 0 + || context.EMax.CompareTo(EInteger.FromInt32(Math.Max(324, digits) + 1)) < 0)) + return; + var u = Math.Pow(10, 1 - digits); + ScaledTolerance = k * t * (1 + u) * (1 + 1e-12); + ScaledRounding = k * levels * u; + Applies = true; + } + + /// The gate for the settings in force. + internal static MachineNumberGate Current() + { + var context = MathS.Settings.DecimalPrecisionContext.Value; + var tolerance = MathS.Settings.PrecisionErrorZeroRange.Value; + var maxValue = MathS.Settings.MaxAbsNumeratorOrDenominatorValue.Value; + var iterCount = MathS.Settings.FloatToRationalIterCount.Value; + var toleranceOverridden = MathS.Settings.PrecisionErrorZeroRange.IsOverriden; + var gate = System.Threading.Volatile.Read(ref last); + if (gate is not null && ReferenceEquals(gate.context, context) && ReferenceEquals(gate.tolerance, tolerance) + && ReferenceEquals(gate.maxValue, maxValue) && gate.iterCount == iterCount + && gate.toleranceOverridden == toleranceOverridden) + return gate; + gate = new MachineNumberGate(context, tolerance, maxValue, iterCount, toleranceOverridden); + System.Threading.Volatile.Write(ref last, gate); + return gate; + } + } + } + } + } +} diff --git a/Sources/AngouriMath/Core/Entity/Entity.ImplicitOperators.cs b/Sources/AngouriMath/Core/Entity/Entity.ImplicitOperators.cs index b9de52b31..481b03df1 100644 --- a/Sources/AngouriMath/Core/Entity/Entity.ImplicitOperators.cs +++ b/Sources/AngouriMath/Core/Entity/Entity.ImplicitOperators.cs @@ -58,13 +58,13 @@ partial record Entity /// and not one tenth. Write 0.1m, or a , for the exact /// number. /// - public static implicit operator Entity(float value) => Number.Real.FromMachineNumber(EDecimal.FromSingle(value)); + public static implicit operator Entity(float value) => Number.Real.FromMachineNumber(EDecimal.FromSingle(value), value); /// /// The value as a literal, read as the binary /// it is rather than as the decimal it was written as. /// - public static implicit operator Entity(double value) => Number.Real.FromMachineNumber(EDecimal.FromDouble(value)); + public static implicit operator Entity(double value) => Number.Real.FromMachineNumber(EDecimal.FromDouble(value), value); /// /// The value as a literal. A is @@ -77,7 +77,7 @@ partial record Entity /// parts and their precision. /// public static implicit operator Entity(System.Numerics.Complex value) => - Number.Complex.FromMachineNumbers(EDecimal.FromDouble(value.Real), EDecimal.FromDouble(value.Imaginary)); + Number.Complex.FromMachineNumbers(value.Real, value.Imaginary); /// The big integer as an literal, exactly. public static implicit operator Entity(System.Numerics.BigInteger bigInt) diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs index 006c9f9d8..3b86ffdb2 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs @@ -465,6 +465,13 @@ public Entity Evaled { get { + // A number is its own value at every precision: InnerSimplify answers the number, it has no + // children, and the codomain it was made with -- its own type's, or Any -- contains it, since the + // set of each is a test of the type alone (SpecialSet.MayContain). So the cache below, an object of + // 40 bytes on the first read, held only the number itself. A number given another codomain by + // WithCodomain may evaluate to NaN, and still goes through it. + if (this is Number && (Codomain == DefaultCodomain || Codomain == Domain.Any)) + return this; // Cached with the precision it was computed at, and read back only at that // precision: a hundred digits of pi are the wrong answer at five hundred. The // stamp is the precision setting's frame for this flow, compared by reference. diff --git a/Sources/Tests/UnitTests/Common/PublicApi.txt b/Sources/Tests/UnitTests/Common/PublicApi.txt index a256cd1f3..db33de691 100644 --- a/Sources/Tests/UnitTests/Common/PublicApi.txt +++ b/Sources/Tests/UnitTests/Common/PublicApi.txt @@ -2128,6 +2128,7 @@ AngouriMath.Entity+Number+Real.Codomain { } : AngouriMath.Core.Domain AngouriMath.Entity+Number+Real.CompareTo(AngouriMath.Entity+Number+Real) : System.Int32 AngouriMath.Entity+Number+Real.CompareTo(System.Object) : System.Int32 AngouriMath.Entity+Number+Real.Create(PeterO.Numbers.EDecimal) : AngouriMath.Entity+Number+Real +AngouriMath.Entity+Number+Real.CreateWithoutDowncasting(PeterO.Numbers.EDecimal) : AngouriMath.Entity+Number+Real AngouriMath.Entity+Number+Real.Deconstruct(PeterO.Numbers.EDecimal&) : System.Void AngouriMath.Entity+Number+Real.EDecimal { } : PeterO.Numbers.EDecimal AngouriMath.Entity+Number+Real.EqualityContract { } : System.Type diff --git a/Sources/Tests/UnitTests/Core/AMachineNumberIsMadeAsBeforeTest.cs b/Sources/Tests/UnitTests/Core/AMachineNumberIsMadeAsBeforeTest.cs new file mode 100644 index 000000000..bb0197898 --- /dev/null +++ b/Sources/Tests/UnitTests/Core/AMachineNumberIsMadeAsBeforeTest.cs @@ -0,0 +1,324 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using PeterO.Numbers; +using Xunit; +using static AngouriMath.Entity.Number; + +namespace AngouriMath.Tests.Core +{ + /// + /// A number made from a , a or a is + /// the number 2.7.0 made from it -- the same type, the same decimal, the same text and the same hash -- under the + /// default settings and under every setting the cheaper path reads. is the + /// old code, copied. + /// + [Trait("Area", "Core")] + public sealed class AMachineNumberIsMadeAsBeforeTest + { + private const int Million = 1_000_000; + + /// The failures, a few of them, with their count; an empty string when there are none. + private sealed class Mismatches + { + private int count; + private readonly List first = new(); + internal void Add(string what) + { + if (Interlocked.Increment(ref count) <= 10) + lock (first) + first.Add(what); + } + internal void AssertNone() + => Assert.True(count == 0, $"{count} values made differently, among them:\n" + string.Join("\n", first)); + } + + private static string Describe(Entity e) => $"{e.GetType().Name} {e}"; + + private static bool Same(Entity actual, Entity expected) + => actual.GetType() == expected.GetType() + && actual.Equals(expected) + && actual.GetHashCode() == expected.GetHashCode() + && actual.ToString() == expected.ToString() + && (actual is not Real r || expected is not Real s || r.EDecimal.Equals(s.EDecimal)); + + private static void CheckDouble(double x, Mismatches mismatches) + { + var expected = NumberCreationAsOf270.FromMachineNumber(EDecimal.FromDouble(x)); + Entity viaEntity = x; + Real viaReal = x; + Entity.Number viaNumber = x; + foreach (var actual in new Entity[] { viaEntity, viaReal, viaNumber, MathS.Numbers.Create(x) }) + if (!Same(actual, expected)) + { + mismatches.Add($"{x:R}: {Describe(actual)}, was {Describe(expected)}"); + return; + } + Complex viaComplex = x; + CheckComplexResult(viaComplex, EDecimal.FromDouble(x), EDecimal.Zero, $"{x:R} as a complex", mismatches); + } + + private static void CheckFloat(float x, Mismatches mismatches) + { + var expected = NumberCreationAsOf270.FromMachineNumber(EDecimal.FromSingle(x)); + Entity viaEntity = x; + Real viaReal = x; + foreach (var actual in new Entity[] { viaEntity, viaReal }) + if (!Same(actual, expected)) + { + mismatches.Add($"{x:R}f: {Describe(actual)}, was {Describe(expected)}"); + return; + } + Complex viaComplex = x; + CheckComplexResult(viaComplex, EDecimal.FromSingle(x), EDecimal.Zero, $"{x:R}f as a complex", mismatches); + } + + private static void CheckComplex(double re, double im, Mismatches mismatches) + { + var value = new System.Numerics.Complex(re, im); + Entity viaEntity = value; + Complex viaComplex = value; + CheckComplexResult(viaEntity, EDecimal.FromDouble(re), EDecimal.FromDouble(im), $"{re:R} + {im:R}i", mismatches); + CheckComplexResult(viaComplex, EDecimal.FromDouble(re), EDecimal.FromDouble(im), $"{re:R} + {im:R}i as a complex", mismatches); + } + + private static void CheckComplexResult(Entity actual, EDecimal re, EDecimal im, string input, Mismatches mismatches) + { + var (number, realPart, imaginaryPart) = NumberCreationAsOf270.FromMachineNumbers(re, im); + bool same = number is not null + ? Same(actual, number) + : actual.GetType() == typeof(Complex) + && Same(((Complex)actual).RealPart, realPart!) && Same(((Complex)actual).ImaginaryPart, imaginaryPart!); + if (!same) + mismatches.Add($"{input}: {Describe(actual)}, was {(number is not null ? Describe(number) : $"{Describe(realPart!)} + {Describe(imaginaryPart!)} i")}"); + } + + /// Under the settings opens, in every worker. + private static void Run(int count, Func value, Func? scope = null) + { + var mismatches = new Mismatches(); + Parallel.For(0, Environment.ProcessorCount, worker => + { + using var _ = scope?.Invoke(); + for (var i = worker; i < count; i += Environment.ProcessorCount) + CheckDouble(value(i), mismatches); + }); + mismatches.AssertNone(); + } + + private static double FromBits(int seed, int i) + { + // A value from the bits of a hash of the index: random, reproducible, and the same in every worker. + var bits = unchecked((long)Mix((ulong)seed * 0x9E3779B97F4A7C15UL + (ulong)i)); + var x = BitConverter.Int64BitsToDouble(bits); + return double.IsNaN(x) || double.IsInfinity(x) ? bits * 1e-300 : x; + } + + private static ulong Mix(ulong z) + { + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL; + return z ^ (z >> 31); + } + + /// (r - 1/2) 10^k, r uniform in [0, 1), k in -30..30 in turn. + private static double Scaled(int seed, int i) + => ((Mix((ulong)seed * 0x9E3779B97F4A7C15UL + (ulong)i) >> 11) * (1.0 / (1UL << 53)) - 0.5) * Math.Pow(10, i % 61 - 30); + + private static IEnumerable Neighbours(double x, int ulps) + { + var d = x; + var u = x; + yield return x; + for (var i = 0; i < ulps; i++) + { + d = Math.BitDecrement(d); + u = Math.BitIncrement(u); + yield return d; + yield return u; + } + } + + private static readonly double[] ShortDecimals = + { + 0.1, 0.2, 0.3, 0.05, 0.37, 1.0 / 3, 2.0 / 3, 1.0 / 7, 22.0 / 7, 2.5, 1234.5, 0.125, 0.001, 0.999, 100.01, + 3.14159, 0.7, 1.1, 99999.99, 0.0625, 1e-8, 12345.678, 1.0 / 99999989, 99999989.5, 1e8 + 0.5, + }; + + private static readonly double[] Specials = + { + 0.0, -0.0, double.NaN, double.PositiveInfinity, double.NegativeInfinity, double.Epsilon, -double.Epsilon, + double.MaxValue, double.MinValue, 2.2250738585072014E-308, 2.2250738585072009E-308, 1e-310, -1e-320, 1e-16, + 1e-50, 1e-100, 1e-200, 1e-300, 1e300, 1, -1, 0.5, -0.5, + }; + + private static IEnumerable Edges() + { + foreach (var x in ShortDecimals) + foreach (var n in Neighbours(x, 8)) + { + yield return n; + yield return -n; + } + foreach (var x in new[] { Math.Pow(2, 53), Math.Pow(2, 62), Math.Pow(2, 63), long.MinValue, long.MaxValue, 1e8, 1e9, 1e15, 1e16 }) + foreach (var n in Neighbours(x, 16)) + { + yield return n; + yield return -n; + } + foreach (var x in new[] { 1e-16, 1e-50, 1e-15, 1e-30, 1e-150, 1e-17, 2e-16, 2e-50, 1e-8, 1e-9, 2.5e-9, 1e-10 }) + foreach (var n in Neighbours(x, 8)) + foreach (var shifted in new[] { n, -n, 1 + n, 1 - n, 7 + n, 7 - n, 0.5 + n, 0.5 - n, 1e6 + n, 1e6 - n }) + yield return shifted; + foreach (var x in Specials) + yield return x; + } + + private static readonly List edges = new(Edges()); + + private static readonly Func[] Scopes = + { + () => null, + () => MathS.Settings.DecimalPrecisionContext.Set(new EContext(30, ERounding.HalfUp, -30, 1000, false)), + () => MathS.Settings.DecimalPrecisionContext.Set(new EContext(300, ERounding.HalfUp, -300, 1000, false)), + () => MathS.Settings.DecimalPrecisionContext.Set(new EContext(150, ERounding.HalfEven, -100000, 100000, false)), + () => MathS.Settings.DecimalPrecisionContext.Set(new EContext(29, ERounding.HalfUp, -29, 1000, false)), + () => MathS.Settings.DecimalPrecisionContext.Set(new EContext(20, ERounding.HalfUp, -100, 1000, false)), + () => MathS.Settings.DecimalPrecisionContext.Set(EContext.Unlimited.WithPrecision(100)), + () => MathS.Settings.DecimalPrecisionContext.Set(new EContext(100, ERounding.Down, -100, 1000, false)), + () => MathS.Settings.PrecisionErrorZeroRange.Set(EDecimal.Create(1, -16)), + () => MathS.Settings.PrecisionErrorZeroRange.Set(EDecimal.Create(1, -12)), + () => MathS.Settings.PrecisionErrorZeroRange.Set(EDecimal.Create(1, -30)), + () => MathS.Settings.PrecisionErrorZeroRange.Set(EDecimal.Create(1, -6)), + () => MathS.Settings.MaxAbsNumeratorOrDenominatorValue.Set(EInteger.FromInt32(1000)), + () => MathS.Settings.MaxAbsNumeratorOrDenominatorValue.Set(EInteger.FromInt32(1_000_000_000)), + () => MathS.Settings.MaxAbsNumeratorOrDenominatorValue.Set(EInteger.FromInt64(1_000_000_000_000)), + () => MathS.Settings.FloatToRationalIterCount.Set(1), + () => MathS.Settings.FloatToRationalIterCount.Set(3), + () => MathS.Settings.FloatToRationalIterCount.Set(100), + () => MathS.Settings.FloatToRationalIterCount.Set(200), + () => MathS.Settings.DowncastingEnabled.Set(false), + }; + + [Fact] + public void RandomBitPatterns() => Run(Million, i => FromBits(1, i)); + + [Fact] + public void RandomValuesAtEveryScale() => Run(Million, i => Scaled(2, i)); + + [Fact] + public void EveryRatioOfIntegersUnderAThousand() + { + var ratios = new List(); + for (var q = 1; q < 1000; q++) + for (var p = -q; p <= q; p++) + ratios.Add((double)p / q); + Run(ratios.Count, i => ratios[i]); + } + + [Fact] + public void EdgesUnderTheDefaults() => Run(edges.Count, i => edges[i]); + + [Fact] + public void UnderEverySettingTheCheckReads() + { + foreach (var scope in Scopes) + { + Run(edges.Count, i => edges[i], scope); + Run(20_000, i => FromBits(3, i), scope); + Run(20_000, i => Scaled(4, i), scope); + Run(20_000, i => (double)(i % 1999 - 999) / (i / 1999 % 997 + 1), scope); + } + } + + /// + /// A ratio with a denominator up to past the bound, and the doubles a few ulps from it: where the search finds + /// a ratio the cheaper path must not have refused to look. + /// + private static double NearARatio(int seed, int i) + { + var bits = Mix((ulong)seed * 0x9E3779B97F4A7C15UL + (ulong)i); + var q = 2 + (double)(bits % 200_000_000UL) / Math.Pow(10, (int)(bits >> 40) % 8); + q = Math.Floor(q); + var p = Math.Floor(q * ((bits >> 20) % 1000 / 7.0)) + (bits >> 35) % 3; + var x = p / q; + for (var k = (int)((bits >> 50) % 5); k > 0; k--) + x = (bits >> 55) % 2 == 0 ? Math.BitIncrement(x) : Math.BitDecrement(x); + return (bits >> 60) % 2 == 0 ? x : -x; + } + + [Fact] + public void NearRatiosWithLargeDenominators() + { + Run(200_000, i => NearARatio(12, i)); + foreach (var scope in Scopes) + Run(10_000, i => NearARatio(13, i), scope); + } + + [Fact] + public void Floats() + { + var mismatches = new Mismatches(); + Parallel.For(0, Environment.ProcessorCount, worker => + { + for (var i = worker; i < 300_000; i += Environment.ProcessorCount) + { + var f = BitConverter.Int32BitsToSingle(unchecked((int)Mix(5UL * 0x9E3779B97F4A7C15UL + (ulong)i))); + CheckFloat(float.IsNaN(f) ? 0.1f : f, mismatches); + CheckFloat((float)Scaled(6, i), mismatches); + } + }); + for (var q = 1; q < 300; q++) + for (var p = -q; p <= q; p++) + CheckFloat((float)p / q, mismatches); + foreach (var x in edges) + CheckFloat((float)x, mismatches); + foreach (var f in new[] { float.Epsilon, float.MaxValue, float.MinValue, float.NaN, float.PositiveInfinity, float.NegativeInfinity, 0f, -0f, 1e-40f }) + CheckFloat(f, mismatches); + mismatches.AssertNone(); + } + + [Fact] + public void ComplexNumbers() + { + var mismatches = new Mismatches(); + var imaginaries = new[] { 0.0, -0.0, 1e-60, -1e-60, 1e-40, 1e-16, 0.5, -2.5, 0.1, double.NaN, double.PositiveInfinity, 1.0 / 3 }; + Parallel.For(0, Environment.ProcessorCount, worker => + { + for (var i = worker; i < 100_000; i += Environment.ProcessorCount) + { + CheckComplex(Scaled(7, i), Scaled(8, i), mismatches); + CheckComplex(FromBits(9, i), imaginaries[i % imaginaries.Length], mismatches); + CheckComplex(imaginaries[i % imaginaries.Length], FromBits(10, i), mismatches); + } + }); + foreach (var re in edges) + foreach (var im in imaginaries) + CheckComplex(re, im, mismatches); + mismatches.AssertNone(); + } + + /// + /// The equivalence above holds trivially if nothing takes the cheaper path; at the defaults almost every + /// double does. + /// + [Fact] + public void AlmostEveryDoubleIsDecidedWithoutTheSearch() + { + var decided = 0; + const int count = 100_000; + for (var i = 0; i < count; i++) + if (Real.IsProvablyNoSmallRational(Scaled(11, i) * 1e4 / Math.Pow(10, i % 61 - 30))) + decided++; + Assert.True(decided > count * 0.99, $"{decided} of {count}"); + } + } +} diff --git a/Sources/Tests/UnitTests/Core/ANumberEvaluatesToItselfTest.cs b/Sources/Tests/UnitTests/Core/ANumberEvaluatesToItselfTest.cs new file mode 100644 index 000000000..f1f5467da --- /dev/null +++ b/Sources/Tests/UnitTests/Core/ANumberEvaluatesToItselfTest.cs @@ -0,0 +1,96 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using AngouriMath.Core; +using PeterO.Numbers; +using Xunit; +using static AngouriMath.Entity.Number; + +namespace AngouriMath.Tests.Core +{ + /// + /// of a number is the number itself -- the same instance, at every precision, scoped + /// or not, read first or again -- as it was when the value was cached; and a number given a codomain that does not + /// contain it still evaluates to NaN. + /// + [Trait("Area", "Core")] + public sealed class ANumberEvaluatesToItselfTest + { + private static IEnumerable Numbers() + { + yield return Integer.Zero; + yield return Integer.One; + yield return Integer.Create(-7); + yield return Integer.Create(EInteger.FromString("123456789012345678901234567890")); + yield return Rational.Create(1, 3); + yield return Rational.Create(-22, 7); + yield return 0.1; + yield return 1e-200; + yield return Real.CreateWithoutDowncasting(EDecimal.FromString("0.5")); + yield return Real.NaN; + yield return Real.PositiveInfinity; + yield return Real.NegativeInfinity; + yield return Complex.Create(1, 2); + yield return Complex.Create(0.1, -1e-30); + yield return Complex.ImaginaryOne; + yield return new System.Numerics.Complex(double.NaN, 1); + yield return MathS.pi.EvalNumerical(); + yield return MathS.e.EvalNumerical(); + } + + private static void EachIsItself(string where) + { + foreach (var number in Numbers()) + { + Assert.True(ReferenceEquals(number, number.Evaled), $"{number} at {where}"); + Assert.True(ReferenceEquals(number, number.Evaled), $"{number} read again at {where}"); + Assert.True(number.EvaluableNumerical, $"{number} at {where}"); + Assert.True(ReferenceEquals(number, number.EvalNumerical()), $"{number} at {where}"); + } + } + + [Fact] public void AtTheDefaults() => EachIsItself("the defaults"); + + [Fact] public void UnderPrecisionScopes() + { + foreach (var digits in new[] { 5, 30, 100, 300 }) + { + using var _ = MathS.Settings.DecimalPrecisionContext.Set(new EContext(digits, ERounding.HalfUp, -digits, 1000, false)); + EachIsItself($"{digits} digits"); + using (MathS.Settings.DecimalPrecisionContext.Set(EContext.Unlimited.WithPrecision(digits + 7))) + EachIsItself($"{digits + 7} digits, nested"); + EachIsItself($"{digits} digits, after a nested scope"); + } + EachIsItself("the defaults, after the scopes"); + } + + [Fact] public void WithTheDowncastingOff() + { + using var _ = MathS.Settings.DowncastingEnabled.Set(false); + EachIsItself("downcasting off"); + } + + [Fact] public void OnEveryThread() + => Parallel.For(0, 64, i => + { + using var _ = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(20 + i)); + EachIsItself($"{20 + i} digits on a thread"); + }); + + [Fact] public void ANumberOutsideItsCodomainIsNaN() + { + Assert.Equal(MathS.NaN, Rational.Create(1, 3).WithCodomain(Domain.Integer).Evaled); + Assert.Equal(MathS.NaN, Complex.Create(1, 2).WithCodomain(Domain.Real).Evaled); + Assert.Equal(MathS.NaN, ((Entity)0.1).WithCodomain(Domain.Rational).Evaled); + var widened = Integer.Create(5).WithCodomain(Domain.Real); + Assert.True(ReferenceEquals(widened, widened.Evaled)); + } + } +} diff --git a/Sources/Tests/UnitTests/Core/ARealMadeWithoutDowncastingTest.cs b/Sources/Tests/UnitTests/Core/ARealMadeWithoutDowncastingTest.cs new file mode 100644 index 000000000..76311f6f8 --- /dev/null +++ b/Sources/Tests/UnitTests/Core/ARealMadeWithoutDowncastingTest.cs @@ -0,0 +1,84 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using System.Collections.Generic; +using PeterO.Numbers; +using Xunit; +using static AngouriMath.Entity.Number; + +namespace AngouriMath.Tests.Core +{ + /// + /// is under a scope that turns the + /// downcasting off -- the same type, decimal, text and hash -- under any settings, and leaves the settings alone. + /// + [Trait("Area", "Core")] + public sealed class ARealMadeWithoutDowncastingTest + { + private static IEnumerable Values() + { + var random = new Random(17); + foreach (var s in new[] { "0", "-0", "1", "-1", "0.5", "1E+3", "1000", "0.1", "0.3333333333333333333333", "1E-20", "1E-200", + "123456789012345678901234567890", "NaN", "Infinity", "-Infinity", "2.5000", "7E-1" }) + yield return EDecimal.FromString(s); + for (var i = 0; i < 20_000; i++) + { + var x = (random.NextDouble() - 0.5) * Math.Pow(10, random.Next(-30, 31)); + yield return EDecimal.FromDouble(x); + yield return EDecimal.FromDouble(Math.Round(x)); + yield return ERational.Create(random.Next(-1000, 1000), random.Next(1, 1000)).ToEDecimal(EContext.ForPrecision(100)); + } + } + + private static Real Reference(EDecimal value) + { + using var _ = MathS.Settings.DowncastingEnabled.Set(false); + return Real.Create(value); + } + + private static void Check() + { + foreach (var value in Values()) + { + var expected = Reference(value); + var actual = Real.CreateWithoutDowncasting(value); + Assert.Equal(typeof(Real), actual.GetType()); + Assert.Equal(expected.GetType(), actual.GetType()); + Assert.Equal(expected, actual); + Assert.Equal(expected.GetHashCode(), actual.GetHashCode()); + Assert.Equal(expected.ToString(), actual.ToString()); + Assert.True(expected.EDecimal.Equals(actual.EDecimal), value.ToString()); + Assert.True(ReferenceEquals(value, actual.EDecimal), value.ToString()); + } + } + + [Fact] public void AtTheDefaults() => Check(); + + [Fact] public void WithTheDowncastingOff() + { + using var _ = MathS.Settings.DowncastingEnabled.Set(false); + Check(); + } + + [Fact] public void AtThirtyAndThreeHundredDigits() + { + foreach (var digits in new[] { 30, 300 }) + { + using var _ = MathS.Settings.DecimalPrecisionContext.Set(new EContext(digits, ERounding.HalfUp, -digits, 1000, false)); + Check(); + } + } + + [Fact] public void LeavesTheDowncastingOn() + { + Real.CreateWithoutDowncasting(EDecimal.FromString("0.5")); + Assert.True(MathS.Settings.DowncastingEnabled); + Assert.IsType(Real.Create(EDecimal.FromString("0.5"))); + } + } +} diff --git a/Sources/Tests/UnitTests/Core/NumberCreationAsOf270.cs b/Sources/Tests/UnitTests/Core/NumberCreationAsOf270.cs new file mode 100644 index 000000000..93dc4f9f7 --- /dev/null +++ b/Sources/Tests/UnitTests/Core/NumberCreationAsOf270.cs @@ -0,0 +1,444 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using PeterO.Numbers; +using static AngouriMath.Entity.Number; + +namespace AngouriMath.Tests.Core +{ + /// + /// The making of a number from a machine number as it was at 2.7.0 (840075ab2), copied verbatim, so that what + /// the library makes now can be compared with it value by value. Only what a test cannot reach is changed: a + /// that is not downcast is made with the downcasting off, which is what made it then, and + /// a is described by its parts, whose constructor is the library's own. + /// + internal static class NumberCreationAsOf270 + { + /// A real number as the downcasting does not touch it. + private static Real NewReal(EDecimal value) + { + using var _ = MathS.Settings.DowncastingEnabled.Set(false); + return Real.Create(value); + } + + /// Real.FromMachineNumber. + internal static Real FromMachineNumber(EDecimal value) => Create(value, fromMachineNumber: true, EDecimal.One); + + /// + /// Complex.FromMachineNumbers: the number, or, where it has an imaginary part, the two parts it is + /// made of. + /// + internal static (Real? Number, Real? RealPart, Real? ImaginaryPart) FromMachineNumbers(EDecimal real, EDecimal imaginary) + { + if (!MathS.Settings.DowncastingEnabled) + return (null, NewReal(real), NewReal(imaginary)); + Real Part(EDecimal part) => FromMachineNumber(part); + if (imaginary.IsZero) + return (Part(real), null, null); + if (real.IsNaN() || imaginary.IsNaN()) + return (Real.NaN, null, null); + if (imaginary.IsFinite && imaginary.Abs().LessThan(MathS.Settings.DowncastingTolerance)) + return (Part(real), null, null); + else + return (null, Part(real), Part(imaginary)); + } + + private static Real Create(EDecimal value, bool fromMachineNumber, EDecimal cancelledScale) + { + if (!MathS.Settings.DowncastingEnabled) + return NewReal(value); + + if (!value.IsFinite) + return NewReal(value); + // Decided cheaply before the hundred-digit splitting and the search below: + // a value that is not near any small rational -- which is what an + // evaluation produces at almost every node -- is a Real and nothing else. + // https://github.com/asc-community/AngouriMath/issues/1338 + if (!MayBeASmallRational(value, MathS.Settings.FloatToRationalIterCount, MathS.Settings.DowncastingToleranceAsDouble)) + return NewReal(value); + var (intPart, intRest) = value.SplitDecimal(); + // If the difference between value & round(value) is zero (see Number.IsZero), we consider value as an integer. + // Onto zero only as a residual of the cancellation that produced it, below the tolerance times the + // scale of what cancelled; a negative one reaches zero by rounding up. + var tolerance = MathS.Settings.DowncastingTolerance; + bool IsAResidual() => value.IsZero || !cancelledScale.IsZero && value.Abs().LessThan(tolerance.Multiply(cancelledScale.Abs())); + if (intRest.LessThan(tolerance) && (!intPart.IsZero || IsAResidual())) + return Integer.Create(intPart); + if (intRest.GreaterThan(1 - tolerance) && (!intPart.Increment().IsZero || IsAResidual())) + return Integer.Create(intPart.Increment()); + + var attempt = FindRationalWithin(value, fromMachineNumber ? MathS.Settings.PrecisionErrorZeroRange : tolerance); + if (attempt is null || + attempt.ERational.Numerator.Abs() > MathS.Settings.MaxAbsNumeratorOrDenominatorValue || + attempt.ERational.Denominator.Abs() > MathS.Settings.MaxAbsNumeratorOrDenominatorValue) + return NewReal(value); + else + return attempt; + } + + + /// + /// , accepting a level of the continued fraction whose + /// remainder is below its integer part times . + /// + internal static Rational? FindRationalWithin(EDecimal num, EDecimal tolerance, int iterCount = int.MinValue) + { + if (iterCount is int.MinValue) + iterCount = MathS.Settings.FloatToRationalIterCount; + if (iterCount <= 0) + return null; + if (!num.IsFinite) + return null; + // The search below is a continued fraction in hundred-digit arithmetic, and + // it is run on the result of every arithmetic operation on a Real, so that + // 0.5 comes back as 1/2: twenty microseconds a time, most of the cost of a + // numerical evaluation (https://github.com/asc-community/AngouriMath/issues/1338). + // Almost every result is not a small rational, and that is decided first in + // a double and then a double-double, whose thirty-two digits are enough to + // say so reliably; only a value the cheap search does not rule out reaches + // the exact one. + if (!MayBeASmallRational(num, iterCount)) + return null; + return FindRationalExactly(num, iterCount, tolerance); + } + + /// The continued fraction in the decimal's own arithmetic, level by level. + internal static Rational? FindRationalExactly(EDecimal num, int iterCount, EDecimal tolerance) + { + if (iterCount <= 0) + return null; + var sign = num.Sign; + num *= sign; + var (intPart, rest) = num.SplitDecimal(); + if (intPart > MathS.Settings.MaxAbsNumeratorOrDenominatorValue) + return null; + // Whether the continued fraction has terminated is a question about the + // digits of intPart, so the tolerance is relative to it. Number.IsZero + // compares against PrecisionErrorZeroRange outright, which at the top of + // the recursion -- where intPart is 0 and rest is the whole number -- + // declared every value below 1e-16 to be the integer 0. That is how + // 1e-20 came to parse as 0. Below the top, intPart is at least 1 (rest + // was inverted to get here), so the test stays as permissive as it was. + if (rest.Abs().LessThan(EDecimal.FromEInteger(intPart) + .Multiply(tolerance, MathS.Settings.DecimalPrecisionContext))) + return Integer.Create(sign * intPart); + else + { + var inv = Entity.Number.CtxDivide(EDecimal.One, rest); + var rat = FindRationalExactly(inv, iterCount - 1, tolerance); + if (rat is null) + return null; + // Through Create, so that a whole number is an Integer: a value just below one is 0 + 1/1, and + // came back as the Rational 1/1, which is not equal to 1. + // https://github.com/asc-community/AngouriMath/issues/2069 + return Rational.Create(intPart * sign + sign / rat.ERational); + } + } + + /// + /// Whether may be within the exact search's tolerance of a + /// rational with a numerator and a denominator within + /// , decided by the + /// same continued fraction in and, where the double cannot + /// tell, in a double-double. A is reliable; a + /// is only a reason to run the exact search. + /// + /// + /// + /// The exact search accepts a level whose remainder is below the integer part + /// times its tolerance, at most , + /// ten to the minus sixteen, unless a caller has set it higher. In a double the remainder at a level carries an error of the value's + /// representation error, two to the minus fifty-two, times the square of that + /// level's convergent denominator; the tolerance here is the exact one widened by + /// that bound, so a value the exact search would accept is never refused, and + /// where the bound has grown past a tenth the double can no longer tell. A + /// double-double -- a pair of doubles, a hundred and six bits -- starts from an + /// error of ten to the minus twenty-eight, which the square of any denominator + /// within the bound leaves below ten to the minus twelve, so it decides every + /// value the double could not. A false yes costs the exact search, which then + /// refuses; it was what every value paid. + /// + /// + /// Both are read off the mantissa's leading bits and the exponent directly: + /// PeterO's own conversions to a double or a decimal round the whole + /// hundred-digit mantissa and cost two to three microseconds, as much as the + /// arithmetic they were meant to spare. The decimal ran fifteen divisions of + /// where the double-double runs fifteen of a few + /// floating-point operations each, and a value near a short decimal -- a + /// polynomial at 0.37000000000001234 is near one at every node -- paid two + /// microseconds in it. + /// + /// + internal static bool MayBeASmallRational(EDecimal num, int iterCount, double integerTolerance = 0) + { + var bound = EDecimal.FromEInteger(MathS.Settings.MaxAbsNumeratorOrDenominatorValue.Value).ToDouble(); + // In a double first, which is a third of a microsecond and refuses most + // values; what it does not refuse, the same search in the double-double + // the value was read as; and only then the exact one. + if (!TryReadAsDoubleDouble(num, out var high, out var low)) + return true; + if (high < 0) + (high, low) = (-high, -low); + // Within the caller's tolerance of an integer -- Real.Create's, which + // rounds a residual of exact cancellation such as sin(pi)'s onto zero. + var nearestInteger = Math.Round(high); + if (Math.Abs(high - nearestInteger) <= integerTolerance) + return true; + if (!ContinuedFractionMayTerminate(high, iterCount, bound)) + return false; + // A yes from the double is only a maybe: its tolerance is the exact one + // widened by its error, and by the twelfth level of a value like sin 1 + // that error is a hundredth, so the remainder there was within it of the + // next integer about once in a hundred values -- each of which then paid + // the fifty microseconds of the exact search to be refused. The + // double-double's error at that level is ten to the minus twelve, and it + // decides. https://github.com/asc-community/AngouriMath/issues/1338 + return ContinuedFractionMayTerminate(high, low, iterCount, bound); + } + + /// + /// The continued fraction of in a double: whether it may + /// reach a level the exact search accepts within + /// levels and with every convergent denominator within ; + /// a yes as well where the double's error -- its representation error times the + /// square of a convergent's denominator -- has grown past a tenth before the + /// question was settled. + /// + private static bool ContinuedFractionMayTerminate(double value, int iterCount, double bound) + { + if (value > 1e300) + return false; + // The convergents' denominators, k_n = a_n k_(n-1) + k_(n-2) from k_(-2) = 1 and + // k_(-1) = 0, to stop once they pass the bound; and the absolute error the + // level's remainder carries, the representation error of the value to begin + // with, divided by the square of each fractional part inverted on the way + // (the derivative of 1/f) and one rounding of each division. Checked with + // this epsilon on twelve thousand rationals within the bound and on as many + // values within ten to the minus ten of one against the exact search: none + // refused. + const double epsilon = 1e-15; // the reading's error, an ulp, and margin + double previousDenominator = 1, denominator = 0; + var rest = value; + var error = epsilon * value + 1e-300; + for (var i = 0; i < iterCount; i++) + { + var integral = Math.Floor(rest); + if (integral > bound) + return false; + var fractional = rest - integral; + var nextDenominator = integral * denominator + previousDenominator; + if (nextDenominator > bound) + return false; + if (error > 0.1) + return true; + // Within the error of a remainder the exact search accepts, or of the + // next integer, where the true integral part is one more and the true + // remainder small. + if (fractional <= integral * 1e-16 + error || 1 - fractional <= error || (integral == 0 && fractional == 0)) + return true; + error = error / (fractional * fractional) + epsilon / fractional; + (previousDenominator, denominator) = (denominator, nextDenominator); + rest = 1 / fractional; + } + return false; + } + + /// + /// The same in a double-double + , + /// whose error stays below deciding for every denominator within the bound. + /// + private static bool ContinuedFractionMayTerminate(double high, double low, int iterCount, double bound) + { + // The reading's relative error -- the mantissa past its hundred and sixth + // bit, the powers of ten from the table, together a rounding of the + // hundred and fourth bit for each of the digits of the exponent (see + // ScalingSteps), and the products' own -- and a division's. + const double epsilonRead = 1e-28; + const double epsilonDivide = 1e-31; + double previousDenominator = 1, denominator = 0; + var error = epsilonRead * high + 1e-300; + for (var i = 0; i < iterCount; i++) + { + var integral = Math.Floor(high); + if (integral == high && low < 0) + integral -= 1; + if (integral > bound) + return false; + var (fractional, fractionalLow) = Subtract(high, low, integral); + var nextDenominator = integral * denominator + previousDenominator; + if (nextDenominator > bound) + return false; + if (error > 0.1) + return true; + if (fractional <= integral * 1e-16 + error || 1 - fractional <= error || (integral == 0 && fractional == 0)) + return true; + error = error / (fractional * fractional) + epsilonDivide / fractional; + (previousDenominator, denominator) = (denominator, nextDenominator); + (high, low) = Reciprocal(fractional, fractionalLow); + } + return false; + } + + // Double-double arithmetic: a value as the unevaluated sum of two doubles, the + // low one within half an ulp of the high one, which is a hundred and six bits. + // Dekker's error-free transformations, without a fused multiply-add, which + // netstandard2.0 does not have. + + /// The sum and its rounding error, exactly. + private static (double Sum, double Error) TwoSum(double a, double b) + { + var sum = a + b; + var bVirtual = sum - a; + var error = (a - (sum - bVirtual)) + (b - bVirtual); + return (sum, error); + } + + /// The sum and its rounding error, where |a| is at least |b|. + private static (double Sum, double Error) QuickTwoSum(double a, double b) + { + var sum = a + b; + return (sum, b - (sum - a)); + } + + /// The product and its rounding error, exactly. + private static (double Product, double Error) TwoProduct(double a, double b) + { + var product = a * b; + const double splitter = 134217729.0; // 2^27 + 1 + var t = splitter * a; + var aHigh = t - (t - a); + var aLow = a - aHigh; + t = splitter * b; + var bHigh = t - (t - b); + var bLow = b - bHigh; + var error = ((aHigh * bHigh - product) + aHigh * bLow + aLow * bHigh) + aLow * bLow; + return (product, error); + } + + /// A double-double minus a double. + private static (double High, double Low) Subtract(double high, double low, double subtrahend) + { + var (sum, error) = TwoSum(high, -subtrahend); + return QuickTwoSum(sum, error + low); + } + + /// A double-double times a double-double. + private static (double High, double Low) Multiply(double aHigh, double aLow, double bHigh, double bLow) + { + var (product, error) = TwoProduct(aHigh, bHigh); + return QuickTwoSum(product, error + aHigh * bLow + aLow * bHigh); + } + + /// One over a double-double, by two Newton corrections of the double's quotient. + private static (double High, double Low) Reciprocal(double high, double low) + { + var quotient = 1 / high; + // The remainder 1 - quotient * (high + low), in a double-double. + var (product, productError) = TwoProduct(quotient, high); + var (remainder, remainderError) = TwoSum(1, -product); + remainderError -= productError + quotient * low; + var correction = (remainder + remainderError) / high; + return QuickTwoSum(quotient, correction); + } + + /// + /// Ten to every power from - to + /// as double-doubles, the positive ones by + /// repeated multiplication -- an error within a rounding of the hundred and + /// fourth bit each, so under two to the minus ninety-five at the end of the + /// table -- and the negative ones their reciprocals. + /// + private const int PowersOfTenRange = 512; + /// + /// How many times the table's range the reading covers: a power of ten in the + /// table carries a rounding of the hundred and sixth bit for each of the + /// multiplications that built it, so the reading's error grows with the + /// exponent, and the ten to the minus twenty-eight the search assumes has room + /// for four thousand digits. + /// + private const int ScalingSteps = 8; + private static readonly (double[] High, double[] Low) powersOfTen = BuildPowersOfTen(); + private static (double[] High, double[] Low) BuildPowersOfTen() + { + var high = new double[2 * PowersOfTenRange + 1]; + var low = new double[2 * PowersOfTenRange + 1]; + double h = 1, l = 0; + for (var n = 0; n <= PowersOfTenRange; n++) + { + high[PowersOfTenRange + n] = h; + low[PowersOfTenRange + n] = l; + (high[PowersOfTenRange - n], low[PowersOfTenRange - n]) = n == 0 ? (1d, 0d) : Reciprocal(h, l); + (h, l) = Multiply(h, l, 10, 0); + } + return (high, low); + } + + /// + /// as a double-double to within ten to the minus + /// twenty-eight relative, from the leading hundred and six bits of its mantissa + /// and its exponent, without rounding the whole mantissa; + /// where the value or its exponent is outside what the reading covers. + /// + private static bool TryReadAsDoubleDouble(EDecimal num, out double high, out double low) + { + high = low = 0; + if (!num.IsFinite) + return false; + var exponent = num.Exponent; + if (!exponent.CanFitInInt32()) + return false; + var decimalExponent = exponent.ToInt32Unchecked(); + if (decimalExponent > ScalingSteps * PowersOfTenRange || decimalExponent < -ScalingSteps * PowersOfTenRange) + return false; + var mantissa = num.UnsignedMantissa; + if (mantissa.IsZero) + return true; + var bits = mantissa.GetUnsignedBitLengthAsInt64(); + // The value's magnitude, within a double's range with room for the four + // partial products below. + var magnitude = (bits + 1) * 0.30102999566398120 + decimalExponent; + if (magnitude > 290 || magnitude < -290) + return false; + var shift = bits > 106 ? (int)(bits - 106) : 0; + var top = shift == 0 ? mantissa : mantissa.ShiftRight(shift); + var upper = top.ShiftRight(53); + var lower = top.Subtract(upper.ShiftLeft(53)); + // upper * 2^53 is exact in a double, and the sum with the lower fifty-three + // bits is exact in the pair. + (high, low) = TwoSum((double)upper.ToInt64Checked() * 9007199254740992.0, (double)lower.ToInt64Checked()); + // The binary shift and the decimal exponent applied in pieces, in turn, + // since either alone can be far outside a double's range while the value is + // not -- a five-hundred-digit mantissa is shifted by sixteen hundred bits. + // A power of two with a whole exponent is exact, so scaling by it is; a + // power of ten comes from the table. Two pieces reach five hundred digits; + // past that, as many as keep each power of ten within the table and each + // power of two within a double -- two halves of a thousand-digit value's + // shift were 2^1608 each, an infinity, and every value at a thousand + // digits went to the exact search. + // https://github.com/asc-community/AngouriMath/issues/1338 + var pieces = Math.Max(2, Math.Max( + (Math.Abs(decimalExponent) + PowersOfTenRange - 1) / PowersOfTenRange, + (shift + 1000 - 1) / 1000)); + var exponentLeft = decimalExponent; + var shiftLeft = shift; + for (var piece = pieces; piece > 0; piece--) + { + var exponentPiece = exponentLeft / piece; + var shiftPiece = shiftLeft / piece; + (high, low) = Multiply(high, low, powersOfTen.High[PowersOfTenRange + exponentPiece], powersOfTen.Low[PowersOfTenRange + exponentPiece]); + var scale = Math.Pow(2, shiftPiece); + (high, low) = (high * scale, low * scale); + exponentLeft -= exponentPiece; + shiftLeft -= shiftPiece; + } + if (num.IsNegative) + (high, low) = (-high, -low); + return !double.IsInfinity(high) && !double.IsNaN(high); + } + } +}