diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 9d3e6e7b8..ade8a0eb8 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -442,6 +442,39 @@ integer. Exact large integers are unchanged | `"integral(exp(x), x, 0, 300)".Simplify()` | `1942426395…4199999…9` | `e ^ 300 - 1` | | `"2^340 * sqrt(2)".Evaled` | an `Integer` | `3.167477390…E+102`, a `Real` | +### A constant near a rational is not taken for it + +**Silent: wrong answers become right ones, or stay written.** Evaluation rounds a value within `1e-50` of a small +rational onto it, at the default hundred digits, so that a cancellation such as `cosh(1)^2 - sinh(1)^2` comes out as +the integer it is. `Simplify` took that rational as the exact value of any constant that is only near one, and the +trigonometric tables read an angle that near a table angle as it. Such a value is now held to an interval +enclosure in twice the working digits, and more where the parts are large or small. It is taken only where the +enclosure holds it; where the enclosure excludes it the constant stays written. An equality or an order of such a +side is decided by the enclosures. A tangent, cotangent, secant or cosecant of an argument whose period the working +digits cannot place is left written instead of `NaN`. A floor, a ceiling, a rounding or a remainder whose argument is +within that distance of where its answer changes is read from the enclosure, or left written +([#2775](https://github.com/asc-community/AngouriMath/issues/2775)). + +| `.Simplify()` | Was (`a3f3b9ed1`) | Now | +|---|---|---| +| `1 - e^(-200)` | `1` | `1 - 1 / e ^ 200` | +| `sinh(60)/cosh(60)` | `1` | `(e ^ 60 + (-1) / e ^ 60) / (e ^ 60 + 1 / e ^ 60)` | +| `sqrt(10^120 + 1) / 10^60` | `1` | `sqrt(10…01) / 10…0` | +| `1/3 + e^(-200)` | `1/3` | `1/3 + 1 / e ^ 200` | +| `cos(1/10^60)` | `1` | `cos(1/10…0)` | +| `sin(1/10^99)` | `0` | `sin(1/10…0)` | +| `arctan(1/10^150)` | `0` | `arctan(1/10…0)` | +| `sin(pi + 1/10^150)` | `0` | `sin(1/10…0 + pi)` | +| `tan(e^1000)` | `NaN` | `tan(e ^ 1000)` | +| `csc(e^1000)^2 - cot(e^1000)^2` | `NaN` | `1` | +| `1 - e^(-200) = 1` | `True` | `False` | +| `cos(1/10^30) < 1` | `False` | `True` | +| `floor(1 - e^(-200))` | `1` | `0` | +| `ceil(1 + e^(-200))` | `1` | `2` | +| `round(1/2 + e^(-200))` | `0` | `1` | +| `(-e^(-1000)) mod 1` | `1` | `1 + (-1) / e ^ 1000` | +| `(7/2 - e^(-200)) mod 1` | `1/2` | `1/2 + (-1) / e ^ 200` | + ### A complex number with exact parts keeps them exact **Silent: wrong numbers become right ones.** A sum, difference, product or quotient of two complex numbers, and so a @@ -503,6 +536,45 @@ before v3, which decides exact comparisons exactly (#1019 §10). Two decimals th | `sqrt(5)^1000 = 5^500` | `False` | stays written | | `sqrt(2) < sqrt(2) + 10^(-150)` | `False` | stays written | +### A value past the exponent range is not taken for 0, an infinity or NaN + +**Silent: wrong answers become right ones, or stay written.** A constant expression whose value is past the decimals' +exponent range evaluates to `+oo`, or flushes to `0`. `Simplify` took those values as exact whenever a function, a +quotient or a comparison held such a part: `e^400000 / e^399999` evaluated as `+oo / +oo` and became `NaN`, and +`1 / e^400000` and `sin(e^(-400000))` became `0`. A part counts as finite when it is written with exact numbers and +constants using sums, products, quotients by parts that cannot be 0, powers, the factorial off its poles, sine, +cosine and erf. A value that rests on such a part is no longer taken from the decimals, and the rest of `Simplify` +decides it or leaves it written. An equality with such a side is not decided by the decimals either. +`(n - 1/2)!` is written out as a rational times `sqrt(pi)` only up to `2 n = 50000`. Past that it stays a factorial, +since it used to take a second or more to write out. A quotient of two factorials of rationals a whole number below +20 apart is the product of the terms that do not cancel +([#2753](https://github.com/asc-community/AngouriMath/issues/2753)). + +| | Was (2.10.0) | Now | +|---|---|---| +| `"exp(400000) * exp(-399999)".Simplify()` | `NaN` | `e` | +| `"e^400000 / e^399999".Simplify()` | `NaN` | `e` | +| `"gamma(300000.5) / gamma(299999.5)".Simplify()` | `NaN` | `599999/2` | +| `"exp(-400000)".Simplify()` | `0` | `1 / e ^ 400000` | +| `"1 / (e^400000 + 1)".Simplify()` | `0` | `1 / (1 + e ^ 400000)` | +| `"exp(-250000) * 10^100000".Simplify()` | `0` | `1000…000 / e ^ 250000` | +| `"abs(e^(-400000))".Simplify()` | `0` | `1 / e ^ 400000` | +| `"sin(e^(-400000))".Simplify()` | `0` | `sin(1 / e ^ 400000)` | +| `"arcsin(e^(-400000))".Simplify()` | `0` | `arccsc(e ^ 400000)` | +| `"sin(e^400000)".Simplify()` | `NaN` | `sin(e ^ 400000)` | +| `"e^(-400000) = 0".Simplify()` | `True` | `False` | +| `"e^400000 = e^400001".Simplify()` | `True` | `e ^ 400000 = e ^ 400001` | +| `"gamma(100001/2)".Simplify()` | `+oo` | `(99999/2)!` | +| `"cos(e^(-400000))".Simplify()` | `1`, which is not its value | `cos(1 / e ^ 400000)` | +| `"floor(-e^(-400000))".Simplify()` | `0` | `-1` | +| `"ceil(e^(-400000))".Simplify()` | `0` | `1` | +| `"(-e^(-400000)) mod 1".Simplify()` | `0` | `1 - 1 / e ^ 400000` | + +`floor`, `ceil`, `round` and `mod 1` of such a value are read from its sign and a bound its parts prove: a power of a +base above 1 to a negative exponent, or a bounded constant over such a power, lies strictly between -1 and 1. So +`floor(e^(-400000))` is `0` as before, but no longer because the value flushed to 0. The +sign of such a value is decided by its parts too, so `sgn(e^400000)` is `1` as before. + ### A square system is answered exactly whichever order its equations are in **Not silent: a decimal answer is now exact, and a refused system has an answer.** The eliminator took the last diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs index 20e97bfe2..7adab0b23 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/ModulusSolver.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) 2019-2026 Angouri. // AngouriMath is licensed under MIT. // Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. @@ -142,6 +142,7 @@ private static bool RealWhereverItIs(Entity expr, Variable x) // The pieces between neighbouring kinks, closed where they end at one, and on each the // sign every modulus takes, read at a point inside it. Set answer = Set.Empty; + var taken = new List(); for (var i = 0; i <= ends.Count; i++) { Point? left = i == 0 ? null : ends[i - 1]; @@ -204,6 +205,14 @@ private static bool RealWhereverItIs(Entity expr, Variable x) case null: return null; case true: + // A finite set keys its members by their evaluations, and two roots a cancellation leaves + // within the rounding of each other evaluate alike: the roots near 10^-71 and -10^-71 of + // x^4 - 10 x^2 - |x| + 10^-70 were one member, and the answer lacked a root. Two such roots + // not shown to be one number decline. https://github.com/asc-community/AngouriMath/issues/2775 + foreach (var other in taken) + if (other.Exact.Evaled == root.Exact.Evaled && Compare(other, root) != 0) + return null; + taken.Add(root); answer = answer.Unite(new FiniteSet(root.Exact)); break; } diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs index ce39238e8..45baa2d07 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs @@ -53,32 +53,436 @@ public partial record Constant /// private static bool IsAZeroOnlyRoundingMade(Entity node, Entity value) => value is Integer { IsZero: true } - && (node is Mulf or Divf or Powf && CannotBeZero(node) || node is Sumf or Minusf && SignOfANonzero(node) is not null); + && (node is Mulf or Divf or Powf && CannotBeZero(node) || node is Sumf or Minusf && SignOfANonzero(node) is not null + // x mod 1 of an x its parts prove strictly between -1 and 1 and not 0 is not 0: e^(-1000) mod 1, about + // 5e-435, was rounded onto it. https://github.com/asc-community/AngouriMath/issues/2753 + || node is Modf(var dividend, Integer(1)) && SignWithMagnitudeBelow(dividend, Integer.One) is not null); /// - /// Whether is an infinity that only the decimals made. A sum, a product or a - /// power of exact finite numbers, the power's base not zero, is exact and finite, and is an infinity only - /// where the context's exponent range rounds it onto one: an exact power too large to build is the - /// decimal, and a complex product's parts are decimals, so 2^(10^10) and (3 + 4i)^2000 are - /// infinite as evaluated. An infinity counts as exact, and every expression holding one was simplified to - /// it. An operand that is a decimal already is not asked about: its power past the range is the - /// decimal's +oo, as it was. Asked only of a value that is not finite. + /// Whether , the exact number or boolean evaluates to, is one the + /// decimals' exponent range made rather than the value of : a zero that only rounding made, + /// or a value resting on a part flushed to 0 or saturated to an infinity. Every exact shortcut asks it, of one, two + /// and three arguments alike. A function's shortcut asked none of it, so abs(e^(-400000)) was simplified to 0, + /// abs(e^400000) to +oo and arccsc(e^400000) to 0. + /// https://github.com/asc-community/AngouriMath/issues/2753 + /// + private static bool IsAValueOnlyRoundingMade(Entity node, Entity value) + => IsAZeroOnlyRoundingMade(node, value) || HasAPartRoundedPastTheRange(node) + || IsARationalOnlyRoundingMade(node, value) || IsANaNOnlyLostDigitsMade(node, value) + || IsAComparisonOfARounding(node, value) || IsAnIntegerPartAtItsBoundary(node, value); + + /// + /// Whether , the number a floor, a ceiling, a rounding or a remainder of a constant + /// evaluates to, was read from a decimal at the boundary where its answer changes: the argument, or the quotient of + /// a remainder, is within of an integer, or of a half for a + /// rounding, which the decimal cannot tell it from. floor(1 - e^(-200)) was 1 and (-e^(-1000)) mod 1 + /// was 1. The node's own arms decide it by an enclosure instead, or leave it written. + /// https://github.com/asc-community/AngouriMath/issues/2775 + /// + private static bool IsAnIntegerPartAtItsBoundary(Entity node, Entity value) + => value is Number && node switch + { + Floorf(var argument) => IsReadAtABoundary(argument, argument.Evaled, half: false), + Ceilf(var argument) => IsReadAtABoundary(argument, argument.Evaled, half: false), + Roundf(var argument) => IsReadAtABoundary(argument, argument.Evaled, half: true), + Modf(var dividend, var divisor) => divisor.Evaled is Real { IsZero: false } by && dividend.Evaled is Real of + && IsReadAtABoundary(dividend, of / by, half: false), + _ => false + }; + + private static bool IsReadAtABoundary(Entity argument, Entity value, bool half) + { + if (value is not Real { IsFinite: true } real || IsRationalArithmetic(argument) || !IsOfExactNumbers(argument)) + return false; + // An argument whose own value only rounding made is read wrongly wherever it is: (7/2 - e^(-200)) mod 1 was 1/2. + if (RestsOnARounding(argument)) + return true; + var shifted = half ? real.EDecimal.Subtract(PeterO.Numbers.EDecimal.FromString("0.5")) : real.EDecimal; + var distance = shifted.Subtract(shifted.RoundHalfEven()).Abs(); + return distance.CompareTo(MathS.Settings.DowncastingTolerance.Multiply(PeterO.Numbers.EDecimal.Max(PeterO.Numbers.EDecimal.One, shifted.Abs()))) <= 0; + } + + /// + /// less times , taken off its rational terms, + /// so that (7/2 - e^(-200)) mod 1 is 1/2 - 1 / e ^ 200: a sum whose value is near a rational is not + /// gathered by its shortcut, which is how it stays written. + /// + internal static Entity LessAMultiple(Entity expr, Rational unit, Integer times) + { + var (rest, offset) = RationalTermsApart(expr); + var rational = offset - unit * times; + return rest is null ? rational : rational.IsZero ? rest : rational + rest; + } + + /// + /// The integer k with , a real constant, strictly between k and k + 1, + /// as an enclosure in the digits takes shows it; null where the + /// enclosure does not. What a floor, a ceiling, a rounding and a remainder read at their boundary, where the + /// decimal does not tell. https://github.com/asc-community/AngouriMath/issues/2775 + /// + internal static Integer? IntegerPartByEnclosure(Entity expr) + { + if (!IsOfExactNumbers(expr) || Numerics.PreciseEvaluation.Of(expr, DigitsToEnclose(expr)) is not { IsReal: true } enclosure) + return null; + var (low, high) = (enclosure.Re.Low, enclosure.Re.High); + var whole = low.ToEInteger(); + if (low.Sign < 0 && !PeterO.Numbers.EDecimal.FromEInteger(whole).Equals(low)) + whole -= PeterO.Numbers.EInteger.One; + var (lower, upper) = (PeterO.Numbers.EDecimal.FromEInteger(whole), PeterO.Numbers.EDecimal.FromEInteger(whole + PeterO.Numbers.EInteger.One)); + return low.CompareTo(lower) > 0 && high.CompareTo(upper) < 0 ? Integer.Create(whole) : null; + } + + /// + /// Whether , the boolean an equality or an order of two sides evaluates to, compares a side + /// whose value only rounding made: 1 - e^(-200) = 1 was True and cos(1/10^30) < 1 + /// False, the left sides evaluating to 1. https://github.com/asc-community/AngouriMath/issues/2775 + /// + private static bool IsAComparisonOfARounding(Entity node, Entity value) + => value is Boolean + && node switch + { + Equalsf(var left, var right) => (left, right), + Lessf(var left, var right) => (left, right), + LessOrEqualf(var left, var right) => (left, right), + Greaterf(var left, var right) => (left, right), + GreaterOrEqualf(var left, var right) => (left, right), + _ => ((Entity?, Entity?)?)null + } is ({ } l, { } r) + && (RestsOnARounding(l) || RestsOnARounding(r)); + + /// + /// The sign of less , two real constants, where their enclosures in + /// the digits takes are apart; null where they are not. + /// https://github.com/asc-community/AngouriMath/issues/2775 + /// + internal static int? OrderByEnclosures(Entity left, Entity right) + { + var evaluation = Numerics.PreciseEvaluation.In(System.Math.Max(DigitsToEnclose(left), DigitsToEnclose(right))); + if (evaluation.ValueOf(left) is not { IsReal: true } l || evaluation.ValueOf(right) is not { IsReal: true } r) + return null; + return l.Re.High.CompareTo(r.Re.Low) < 0 ? -1 : r.Re.High.CompareTo(l.Re.Low) < 0 ? 1 : null; + } + + /// + /// Whether , the rational or complex rational evaluates to, is one + /// the rounding onto a nearby small rational made, shown by an enclosure of that excludes it. + /// + /// + /// + /// Evaluation rounds a value within of a small rational onto it, + /// ten to the minus fifty at the default hundred digits, so that a cancellation's residual, as in + /// cosh(1)^2 - sinh(1)^2, comes out as the integer it is. A value that only lies that near one came out as it + /// too, and was taken as exact: 1 - e^(-200), sinh(60)/cosh(60) and sqrt(10^120 + 1)/10^60 were + /// simplified to 1. https://github.com/asc-community/AngouriMath/issues/2775 + /// + /// + /// The rounding cannot tell the two apart, and the enclosure is what does: in twice the working digits, and twice + /// as many more as the largest decimal exponent of a part, as e^(-400) in tanh(200) puts the value + /// e^(-400) from 1 where its parts are near e^200. An enclosure that holds the value decides nothing, + /// and the value is taken as it was. Rational terms of a sum are moved to the other side first, so that + /// 1 + e^(-1000) is told from 1 by the enclosure of e^(-1000), which is as narrow as its digits make it. + /// Asked only of a node of exact numbers that is not rational arithmetic, whose value is exact as computed. + /// + /// + private static bool IsARationalOnlyRoundingMade(Entity node, Entity value) + => value is Complex { RealPart: Rational, ImaginaryPart: Rational } exact + && node is not Number + && !IsRationalArithmetic(node) + && IsOfExactNumbers(node) + && EnclosureExcludes(node, exact); + + /// + /// Whether is written of rational and complex rational numbers by sums, differences, + /// products, quotients and integer powers, whose value the evaluation computes exactly. + /// + private static bool IsRationalArithmetic(Entity expr) => expr switch + { + Complex { RealPart: Rational, ImaginaryPart: Rational } => true, + Sumf(var left, var right) => IsRationalArithmetic(left) && IsRationalArithmetic(right), + Minusf(var left, var right) => IsRationalArithmetic(left) && IsRationalArithmetic(right), + Mulf(var left, var right) => IsRationalArithmetic(left) && IsRationalArithmetic(right), + Divf(var left, var right) => IsRationalArithmetic(left) && IsRationalArithmetic(right), + Powf(var @base, Integer) => IsRationalArithmetic(@base), + _ => false + }; + + /// + /// Whether an enclosure of , which has no variables, excludes the rational or complex + /// rational . See . + /// + private static bool EnclosureExcludes(Entity node, Complex exact) + { + var (rest, offset) = RationalTermsApart(node); + if (rest is null || (exact - offset) is not Complex { RealPart: Rational re, ImaginaryPart: Rational im }) + return false; + return Numerics.PreciseEvaluation.Of(rest, DigitsToEnclose(rest)) is { } enclosure + && (Excludes(enclosure.Re, re) || Excludes(enclosure.Im, im)); + } + + private static bool Excludes(Numerics.PreciseInterval interval, Rational value) + => PeterO.Numbers.ERational.FromEDecimal(interval.Low).CompareTo(value.ERational) > 0 + || PeterO.Numbers.ERational.FromEDecimal(interval.High).CompareTo(value.ERational) < 0; + + /// + /// as the sum of its terms that are not rational, null where there are none, and of the + /// rational ones, added up. A node that is not a sum or a difference is its own first part. + /// + private static (Entity? NotRational, Complex Offset) RationalTermsApart(Entity node) + { + if (node is not (Sumf or Minusf)) + return (node, Integer.Zero); + Entity? rest = null; + Complex offset = Integer.Zero; + void Add(Entity term, bool negated) + { + switch (term) + { + case Sumf(var left, var right): + Add(left, negated); + Add(right, negated); + break; + case Minusf(var left, var right): + Add(left, negated); + Add(right, !negated); + break; + case Complex { RealPart: Rational, ImaginaryPart: Rational } number: + offset = negated ? offset - number : offset + number; + break; + default: + rest = rest is null ? (negated ? -term : term) : negated ? rest - term : rest + term; + break; + } + } + Add(node, false); + return (rest, offset); + } + + /// The most digits an enclosure of is worked out to. + private const int MaxEnclosureDigits = 2000; + + /// + /// Twice the working digits, and twice the largest decimal exponent, either way, of a value in + /// , up to : a value its parts' sizes cancel to is told + /// from a rational near it by as many digits as the cancellation takes. + /// + private static int DigitsToEnclose(Entity expr) + { + var precision = MathS.Settings.DecimalPrecisionContext.Value.Precision; + var working = !precision.IsZero && precision.CanFitInInt32() ? precision.ToInt32Unchecked() : 100; + var spread = 0.0; + foreach (var part in expr.Nodes) + if (part.Evaled is Complex value) + spread = System.Math.Max(spread, System.Math.Max(DecimalExponent(value.RealPart.EDecimal), DecimalExponent(value.ImaginaryPart.EDecimal))); + // Rounded up to a hundred, so that the contexts, and the constants cached by context, are shared. + var digits = System.Math.Min(System.Math.Max(2.0 * working, 50) + 2 * spread, MaxEnclosureDigits); + return (int)System.Math.Min(System.Math.Ceiling(digits / 100) * 100, MaxEnclosureDigits); + } + + /// The magnitude of the decimal exponent of , about; 0 for 0 and an infinity. + private static double DecimalExponent(PeterO.Numbers.EDecimal value) + { + if (!value.IsFinite || value.IsZero) + return 0; + if (!value.Exponent.CanFitInInt64()) + return MaxEnclosureDigits; + return System.Math.Abs(value.Exponent.ToInt64Unchecked() + value.Mantissa.Abs().GetUnsignedBitLengthAsInt64() * 0.30103); + } + + /// + /// Whether , the NaN evaluates to, is one only the working + /// digits made: a part of it is a trigonometric function of a finite argument whose sine is NaN, for want of + /// the digits that place the argument within its period. e^1000 is about 2e434, and in a hundred + /// digits its tangent, secant and cosecant were NaN, and were simplified to it, where each is a number. + /// https://github.com/asc-community/AngouriMath/issues/2775 + /// + private static bool IsANaNOnlyLostDigitsMade(Entity node, Entity value) + { + if (!value.IsNaN) + return false; + foreach (var part in node.Nodes) + if (part is Sinf or Cosf or Tanf or Cotanf or Secantf or Cosecantf + && part.DirectChildren[0].Evaled is Complex number && Number.PartsAreFinite(number) && Number.Sin(number).IsNaN) + return true; + return false; + } + + /// + /// Whether is shown not to be the value of , which has no + /// variables: their enclosures, in the digits takes, are apart. A table + /// of exact values is read by an evaluation that agrees with an entry to the working digits, and an angle nearer + /// than that to one was read as it: sin(1/10^99) was 0. https://github.com/asc-community/AngouriMath/issues/2775 + /// + internal static bool IsShownNotToBe(Entity expr, Entity value) + { + var evaluation = Numerics.PreciseEvaluation.In(DigitsToEnclose(expr)); + return evaluation.ValueOf(expr) is { } left && evaluation.ValueOf(value) is { } right + && (Apart(left.Re, right.Re) || Apart(left.Im, right.Im)); + } + + private static bool Apart(Numerics.PreciseInterval left, Numerics.PreciseInterval right) + => left.High.CompareTo(right.Low) < 0 || right.High.CompareTo(left.Low) < 0; + + /// + /// Whether the value of is one only the decimals' exponent range made, so that a rule reading + /// it as exact reads another number: sin(e^(-400000)) looked its argument up in the table of sines as 0. + /// https://github.com/asc-community/AngouriMath/issues/2753 + /// + internal static bool RestsOnARounding(Entity expr) + => expr is not Number && expr.Evaled is (Number or Boolean) and var value && IsAValueOnlyRoundingMade(expr, value); + + /// + /// The sign of where its parts prove it a nonzero real of magnitude below + /// , a rational in (0, 1]; where they do not. Read from the + /// structure and never from the decimals, which flush e^(-400000) to 0: a power of a base above 1 to a + /// negative exponent, a power of a base inside the bound to an exponent of at least 1, a rational at most 1 in + /// magnitude over a part above 1 / bound, and products of those. It is what floor, ceil, + /// round and mod 1 of such a value need, and the decimal that was read for it was 0. + /// https://github.com/asc-community/AngouriMath/issues/2753 + /// + internal static int? SignWithMagnitudeBelow(Entity expr, Rational bound) + { + switch (expr) + { + case Rational r: + return !r.ERational.IsZero && r.ERational.Abs().CompareTo(bound.ERational) < 0 ? r.ERational.Sign : null; + case Variable { IsConstant: true } constant: + return constant.Evaled is Real { IsFinite: true } value && !value.IsZero + && PeterO.Numbers.ERational.FromEDecimal(value.EDecimal.Abs()).CompareTo(bound.ERational) < 0 ? value.EDecimal.Sign : null; + case Powf(var @base, var exponent): + if (Exceeds(@base, Integer.One) && SignOfANonzero(exponent) == -1 + && (bound.ERational.CompareTo(PeterO.Numbers.ERational.One) == 0 + || exponent is Rational atMostMinusOne && atMostMinusOne.ERational.CompareTo(PeterO.Numbers.ERational.FromInt32(-1)) <= 0 + && Exceeds(@base, (Rational)(Integer.One / bound)))) + return 1; + if (SignWithMagnitudeBelow(@base, bound) == 1 && exponent is Rational atLeastOne + && atLeastOne.ERational.CompareTo(PeterO.Numbers.ERational.One) >= 0) + return 1; + return null; + case Divf(var numerator, var denominator): + if (SignOfANonzero(numerator) is { } sign && MagnitudeAtMost(numerator) is { } most + && Exceeds(denominator, Rational.Create(most.Divide(bound.ERational)))) + return sign; + return Exceeds(denominator, Integer.One) ? SignWithMagnitudeBelow(numerator, bound) : null; + case Mulf(Integer { EInteger: var minusOne }, var factor) when minusOne.Equals(PeterO.Numbers.EInteger.FromInt32(-1)): + return -SignWithMagnitudeBelow(factor, bound); + case Mulf(var left, var right): + return SignWithMagnitudeBelow(left, bound) * SignWithMagnitudeBelow(right, Integer.One); + default: + return null; + } + } + + /// + /// Whether base ^ exponent, for a base above 1 and an exponent of at least 1, is above : + /// a rational below the base and above 1, to the whole part of the exponent, is, where the exponent's whole part + /// is at least the base-2 logarithm of the bound, bounded above by its bits, over that of the rational, bounded + /// below. e^400000 is above 3 though e is not. + /// + private static bool PowerExceeds(Entity @base, PeterO.Numbers.ERational exponent, PeterO.Numbers.ERational bound) + { + if (!Exceeds(@base, Integer.One) || MagnitudeAtMost(@base) is null || @base.Evaled is not Real { IsFinite: true } value) + return false; + // Halfway from 1 to the base, which its hundred digits cannot have rounded past. + var below = 1 + (value.EDecimal.ToDouble() - 1) / 2; + if (!(below > 1) || double.IsInfinity(below)) + return false; + var boundBits = bound.Numerator.GetUnsignedBitLengthAsInt64() - bound.Denominator.GetUnsignedBitLengthAsInt64() + 1; + var whole = exponent.Numerator.Divide(exponent.Denominator); + var needed = Math.Ceiling(Math.Max(boundBits, 1) / Math.Log(below, 2)) + 1; + return needed < 1e15 && whole.CompareTo(PeterO.Numbers.EInteger.FromInt64((long)needed)) >= 0; + } + + /// + /// A whole number at least the magnitude of , a real of exact numbers and constants whose + /// value is finite and its own: the rational's own magnitude, or one more than the floor of the decimal's, which a + /// hundred digits cannot have rounded past. otherwise. + /// + private static PeterO.Numbers.ERational? MagnitudeAtMost(Entity expr) + => expr switch + { + Rational r => r.ERational.Abs(), + _ when expr.Evaled is Real { IsFinite: true } value && IsOfExactNumbers(expr) && !RestsOnARounding(expr) + => PeterO.Numbers.ERational.FromEInteger(value.EDecimal.Abs().Floor().ToEInteger().Add(PeterO.Numbers.EInteger.One)), + _ => null + }; + + /// + /// Whether the parts of prove it a real above , a rational of at + /// least 1: a rational or a constant above it, a power of a base above it to an exponent of at least 1, a product + /// of a part above it and one above 1, or a sum of a part above it and a positive one. + /// https://github.com/asc-community/AngouriMath/issues/2753 + /// + private static bool Exceeds(Entity expr, Rational bound) => expr switch + { + Rational r => r.ERational.CompareTo(bound.ERational) > 0, + Variable { IsConstant: true } constant => constant.Evaled is Real { IsFinite: true } value + && PeterO.Numbers.ERational.FromEDecimal(value.EDecimal).CompareTo(bound.ERational) > 0, + Powf(var @base, Rational exponent) => exponent.ERational.CompareTo(PeterO.Numbers.ERational.One) >= 0 + && (Exceeds(@base, bound) || PowerExceeds(@base, exponent.ERational, bound.ERational)), + Powf(var @base, var exponent) => bound.ERational.CompareTo(PeterO.Numbers.ERational.One) == 0 + && Exceeds(@base, Integer.One) && SignOfANonzero(exponent) == 1, + Mulf(var left, var right) => Exceeds(left, bound) && Exceeds(right, Integer.One) || Exceeds(right, bound) && Exceeds(left, Integer.One), + Sumf(var left, var right) => Exceeds(left, bound) && SignOfANonzero(right) == 1 || Exceeds(right, bound) && SignOfANonzero(left) == 1, + _ => false + }; + + /// + /// Whether is finite as written and an infinity, or NaN, as evaluated. A sum, a + /// product or a power of exact finite numbers, the power's base not zero, is exact and finite, and is an infinity + /// only where the context's exponent range rounds it onto one: an exact power too large to build is the decimal, + /// and a complex product's parts are decimals, so 2^(10^10) and (3 + 4i)^2000 are infinite as + /// evaluated. An infinity counts as exact, and every expression holding one was simplified to it. An operand that + /// is a decimal already is not asked about: its power past the range is the decimal's +oo, as it was. /// /// An operand written exactly whose value is a decimal, sqrt(2) or pi, is finite all the same: /// 2^4000 sqrt(2) is about 1.9e1204, past the range, and its +oo was taken as the /// value of the product, so Simplify answered +oo. /// https://github.com/asc-community/AngouriMath/issues/2615 /// + /// + /// So is a quotient, and a NaN such an infinity made: e^400000 evaluates to +oo, so + /// e^400000 / e^399999 evaluated to +oo / +oo, which is NaN, and was simplified to it, where + /// it is e. https://github.com/asc-community/AngouriMath/issues/2753 + /// /// - private static bool IsAnInfinityOnlyRoundingMade(Entity node, Entity value) - => value is Complex number && !Number.PartsAreFinite(number) && !value.IsNaN && node.Nodes.Any(IsFiniteRoundedOntoAnInfinity); - private static bool IsFiniteRoundedOntoAnInfinity(Entity part) - => part is Sumf or Minusf or Mulf or Powf - && part.Evaled is Complex { IsFinite: false } evaluated && !evaluated.IsNaN - && part.DirectChildren.All(static operand => operand.Evaled is Complex finite && IsFiniteExactly(finite) - && (finite.IsExact || !operand.Nodes.Any(static node => node is Number { IsExact: false }))) - && !(part is Powf(var @base, _) && @base.Evaled is Complex { IsZero: true }); + => part is Sumf or Minusf or Mulf or Divf or Powf or Factorialf or Sinf or Cosf or Erff + && part.Evaled is Complex evaluated && !Number.PartsAreFinite(evaluated) + && IsFiniteAsWritten(part); + + /// + /// Whether is a finite number whatever its decimals evaluate to: its value is finite, or it + /// is written of exact numbers and constants by sums, differences and products of finite parts, quotients by parts + /// that cannot be 0, powers of parts that cannot be 0 to finite exponents, and the functions that are finite at + /// every finite argument but their poles: the factorial, and so the gamma function, away from the negative + /// integers, and sine, cosine and erf everywhere. e^400000 is about + /// 1e173717, past the decimals' exponent range, and evaluates to +oo; it is no more infinite than + /// e^400000 + 1 or 1 / e^(-400000). A part with a decimal in it is not asked about: its value past the + /// range is the decimal's +oo, as it was. gamma(300000.5) / gamma(299999.5) evaluated to + /// +oo / +oo and was simplified to NaN, where it is 299999.5. + /// https://github.com/asc-community/AngouriMath/issues/2753 + /// + private static bool IsFiniteAsWritten(Entity expr) + => expr.Evaled is Complex value && IsFiniteExactly(value) + || expr is Sumf or Minusf or Mulf or Divf or Powf or Factorialf or Sinf or Cosf or Erff + && IsOfExactNumbers(expr) && IsFiniteByStructure(expr); + + /// of an expression of exact numbers, read through its structure. + private static bool IsFiniteByStructure(Entity expr) => expr switch + { + _ when expr.Evaled is Complex value && IsFiniteExactly(value) => true, + Sumf(var left, var right) => IsFiniteByStructure(left) && IsFiniteByStructure(right), + Minusf(var left, var right) => IsFiniteByStructure(left) && IsFiniteByStructure(right), + Mulf(var left, var right) => IsFiniteByStructure(left) && IsFiniteByStructure(right), + Divf(var dividend, var divisor) => IsFiniteByStructure(dividend) && CannotBeZero(divisor), + Powf(var @base, var exponent) => CannotBeZero(@base) && IsFiniteByStructure(@base) && IsFiniteByStructure(exponent), + Factorialf(var argument) => argument.Evaled is Complex value && IsFiniteExactly(value) + && !(value is Integer { EInteger.Sign: < 0 }), + Sinf(var argument) => IsFiniteByStructure(argument), + Cosf(var argument) => IsFiniteByStructure(argument), + Erff(var argument) => IsFiniteByStructure(argument), + _ => false + }; /// /// Whether is a number or a constant that is not zero, or a product, @@ -93,8 +497,12 @@ private static bool IsFiniteRoundedOntoAnInfinity(Entity part) Complex number => !number.IsZero && IsFiniteExactly(number), Variable { IsConstant: true } constant => constant.Evaled is Complex { IsZero: false } value && IsFiniteExactly(value), Mulf(var left, var right) => CannotBeZero(left) && CannotBeZero(right), - Divf(var dividend, var divisor) => CannotBeZero(dividend) && divisor.Evaled is Complex value && IsFiniteExactly(value), - Powf(var @base, var exponent) => CannotBeZero(@base) && exponent.Evaled is Complex value && IsFiniteExactly(value), + // A divisor or an exponent past the decimals' exponent range is finite all the same: 1 / e^400000 evaluates + // to 0, and was simplified to it. https://github.com/asc-community/AngouriMath/issues/2753 + Divf(var dividend, var divisor) => CannotBeZero(dividend) && IsFiniteAsWritten(divisor), + Powf(var @base, var exponent) => CannotBeZero(@base) && IsFiniteAsWritten(exponent), + // The gamma function has no zeros, and is finite away from its poles. + Factorialf => IsFiniteAsWritten(expr), _ => SignOfANonzero(expr) is not null }; @@ -142,8 +550,12 @@ private static bool IsFiniteRoundedOntoAnInfinity(Entity part) /// -Q/2 + sqrt(Q^2/4 + P^3/27), the square root about 1.6e-180, evaluated to the rational -Q/2, and /// the quartic formula wrote the roots of another quartic. Walked only where the whole evaluates to an exact /// number. https://github.com/asc-community/AngouriMath/issues/2650 + /// + /// Or a part that is finite and evaluates to an infinity, : an exact value + /// resting on one is no more the whole's value. https://github.com/asc-community/AngouriMath/issues/2753 + /// /// - private static bool HasARootRoundedOntoZero(Entity node) + private static bool HasAPartRoundedPastTheRange(Entity node) { // Recursive and with the arithmetic nodes read directly, so that the walk allocates nothing: it runs on every // exact shortcut, and a stack and the children's enumerators were 1.5 KB on each differentiation. @@ -153,20 +565,22 @@ private static bool HasARootRoundedOntoZero(Entity node) return false; case Mulf or Divf or Powf when node.Evaled is Integer { IsZero: true } && CannotBeZero(node) && IsOfExactNumbers(node): return true; + case Sumf or Minusf or Mulf or Divf or Powf or Factorialf or Sinf or Cosf or Erff when IsFiniteRoundedOntoAnInfinity(node): + return true; case Sumf(var left, var right): - return HasARootRoundedOntoZero(left) || HasARootRoundedOntoZero(right); + return HasAPartRoundedPastTheRange(left) || HasAPartRoundedPastTheRange(right); case Minusf(var left, var right): - return HasARootRoundedOntoZero(left) || HasARootRoundedOntoZero(right); + return HasAPartRoundedPastTheRange(left) || HasAPartRoundedPastTheRange(right); case Mulf(var left, var right): - return HasARootRoundedOntoZero(left) || HasARootRoundedOntoZero(right); + return HasAPartRoundedPastTheRange(left) || HasAPartRoundedPastTheRange(right); case Divf(var left, var right): - return HasARootRoundedOntoZero(left) || HasARootRoundedOntoZero(right); + return HasAPartRoundedPastTheRange(left) || HasAPartRoundedPastTheRange(right); case Powf(var left, var right): - return HasARootRoundedOntoZero(left) || HasARootRoundedOntoZero(right); + return HasAPartRoundedPastTheRange(left) || HasAPartRoundedPastTheRange(right); default: var children = node.DirectChildren; for (var i = 0; i < children.Count; i++) - if (HasARootRoundedOntoZero(children[i])) + if (HasAPartRoundedPastTheRange(children[i])) return true; return false; } @@ -227,8 +641,7 @@ private Entity ExpandOnTwoArguments( bool propagateSet = true, bool settlesNaN = false) { - if (isExact && this.Evaled is (Number { IsExact: true } or Boolean) and var n && !IsAZeroOnlyRoundingMade(this, n) - && !IsAnInfinityOnlyRoundingMade(this, n) && !HasARootRoundedOntoZero(this)) + if (isExact && this.Evaled is (Number { IsExact: true } or Boolean) and var n && !IsAValueOnlyRoundingMade(this, n)) return n; left = left.InnerSimplified(isExact); right = right.InnerSimplified(isExact); @@ -251,8 +664,7 @@ Entity ops(Entity a, Entity b) { if (operation(a, b) is { } res) return res; - if (isExact && defaultCtor(this, a, b) is var built && built.Evaled is Number { IsExact: true } n && !IsAZeroOnlyRoundingMade(built, n) - && !IsAnInfinityOnlyRoundingMade(built, n) && !HasARootRoundedOntoZero(built)) + if (isExact && defaultCtor(this, a, b) is var built && built.Evaled is Number { IsExact: true } n && !IsAValueOnlyRoundingMade(built, n)) return n; return defaultCtor(this, a, b); } @@ -507,7 +919,7 @@ private static (Entity Quantity, int Relation)? SignTest(Entity conjunct) private Entity ExpandOnOneArgument(Entity expr, Func operation, Func defaultCtor, bool isExact, bool propagateSet = true) { - if (isExact && this.Evaled is (Number { IsExact: true } or Boolean) and var n) + if (isExact && this.Evaled is (Number { IsExact: true } or Boolean) and var n && !IsAValueOnlyRoundingMade(this, n)) return n; expr = expr.InnerSimplified(isExact); @@ -518,7 +930,7 @@ Entity ops(Entity a) { if (operation(a) is { } res) return res; - if (isExact && defaultCtor(this, a).Evaled is Number { IsExact: true } n) + if (isExact && defaultCtor(this, a) is var built && built.Evaled is Number { IsExact: true } n && !IsAValueOnlyRoundingMade(built, n)) return n; return defaultCtor(this, a); } @@ -539,7 +951,7 @@ Entity ops(Entity a) private Entity ExpandOnTwoAndTArguments(Entity left, Entity right, T third, Func operation, Func defaultCtor, bool isExact, bool propagateSet = true) { - if (isExact && this.Evaled is (Number { IsExact: true } or Boolean) and var n) + if (isExact && this.Evaled is (Number { IsExact: true } or Boolean) and var n && !IsAValueOnlyRoundingMade(this, n)) return n; left = left.InnerSimplified(isExact); @@ -551,7 +963,7 @@ Entity ops(Entity a, Entity b) { if (operation(a, b, third) is { } res) return res; - if (isExact && defaultCtor(this, a, b, third).Evaled is Number { IsExact: true } n) + if (isExact && defaultCtor(this, a, b, third) is var built && built.Evaled is Number { IsExact: true } n && !IsAValueOnlyRoundingMade(built, n)) return n; return defaultCtor(this, a, b, third); } diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs index 2aa23ffbb..00a3d0d6d 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs @@ -252,6 +252,27 @@ _ when Core.Sets.Cardinality.Absorbed(a, b) is { } larger => larger, } public partial record Divf { + /// + /// p! / q! for rationals p and q a whole number below 20 apart, the product of the terms + /// that do not cancel: (q + 1) (q + 2) ... p, or its reciprocal. A factorial too large to write out stays + /// written, and the quotient of two of them is still this: gamma(300000.5) / gamma(299999.5) is + /// 299999.5, where both evaluate to +oo. Null where neither is a pole and they are not that close. + /// https://github.com/asc-community/AngouriMath/issues/2753 + /// + private static Entity? QuotientOfNearFactorials(Rational top, Rational bottom) + { + if ((top - bottom) is not Integer { EInteger: var apart } || apart.IsZero || apart.Abs().CompareTo(20) >= 0) + return null; + // At a pole, a negative whole number, the quotient is left to the conditions. + if (top is Integer { EInteger.Sign: < 0 } || bottom is Integer { EInteger.Sign: < 0 }) + return null; + var (low, count) = apart.Sign > 0 ? (bottom, apart.ToInt32Checked()) : (top, -apart.ToInt32Checked()); + Rational product = Integer.One; + for (var k = 1; k <= count; k++) + product = (Rational)(product * (low + k)); + return apart.Sign > 0 ? product : (Rational)(Integer.One / product); + } + // Division is undefined when the divisor equals zero private protected override Entity IntrinsicCondition => !Divisor.EqualTo(0); @@ -282,6 +303,7 @@ n0.Evaled is Complex c => rescaled.InnerSimplified(isExact), (Complex n1, Complex n2) when !isExact => n1 / n2, (var n1, Integer(1)) => n1, + (Factorialf(Rational top), Factorialf(Rational bottom)) when QuotientOfNearFactorials(top, bottom) is { } quotient => quotient, // Sizes are not divided: aleph(0) / 2 has no value. // https://github.com/asc-community/AngouriMath/issues/1409 _ when Core.Sets.Cardinality.HasNoValue(a, b) => MathS.NaN, @@ -397,7 +419,14 @@ protected override Entity InnerSimplify(bool isExact) => n0.Evaled is Complex c ? c.IsZero ? MathS.NaN : 0 : new Providedf(0, new Notf(new Equalsf(n0, 0))), - (var n1, Integer(1)) when n1.Evaled is Integer => 0, + // x mod 1 of a nonzero real below 1 in magnitude, as its parts prove it: x, or x + 1 below 0. + // https://github.com/asc-community/AngouriMath/issues/2753 + (var n1, Integer(1)) when SignWithMagnitudeBelow(n1, Integer.One) is { } side => side > 0 ? n1 : (n1 + 1).InnerSimplified(isExact), + (var n1, Integer(1)) when n1.Evaled is Integer && !RestsOnARounding(n1) => 0, + // The floored remainder a - b floor(a / b), the quotient's floor read from an enclosure where the decimal + // is at its boundary: (-e^(-1000)) mod 1 was 1. https://github.com/asc-community/AngouriMath/issues/2775 + (var n1, Rational n2) when isExact && !n2.IsZero && n1.IsConstant && n1 is not Number && n1.Evaled is Real dividendValue && IsReadAtABoundary(n1, dividendValue / n2, half: false) + && IntegerPartByEnclosure(n1 / n2) is { } quotient => LessAMultiple(n1, n2, quotient).InnerSimplified(isExact), // a % a = 0 wherever a % a means anything at all, which is wherever a is // not zero -- and where it is, the whole node is undefined in any case. (var n1, var n2) when n1 == n2 => new Providedf(0, new Notf(new Equalsf(n2, 0))), @@ -1303,6 +1332,16 @@ protected override Entity InnerSimplify(bool isExact) public partial record Factorialf { + /// + /// The largest |2 n| for which (n - 1/2)! is written out as a rational times sqrt(pi). The + /// rational's numerator is (2 n - 1)!, of about 2 n log2(2 n / e) bits, which at 2 n = 10^5 + /// took a second and at 6 * 10^5 more than twenty. Past it the factorial stays written. It was never built + /// that large before: past the decimals' exponent range, which gamma(25000.5) is near, the factorial + /// evaluated to +oo and was taken as that. + /// https://github.com/asc-community/AngouriMath/issues/2753 + /// + private const int MaxHalfIntegerFactorial = 50_000; + // Factorial is defined for non-negative integers in the traditional sense, // but extends to complex numbers via the gamma function: n! = Γ(n+1) // The gamma function has poles at negative integers, so factorial is undefined there, @@ -1321,7 +1360,8 @@ protected override Entity InnerSimplify(bool isExact) => a => a switch { Complex c when !isExact => Number.Factorial(c), - Rational({ Numerator: var num, Denominator: var den }) when den.Equals(2) && (num + 1) / 2 is var en => ( + Rational({ Numerator: var num, Denominator: var den }) when den.Equals(2) && num.Abs().CompareTo(PeterO.Numbers.EInteger.FromInt32(MaxHalfIntegerFactorial)) <= 0 + && (num + 1) / 2 is var en => ( en > 0 // (+n - 1/2)! = (2n-1)!/(2^(2n-1)(n-1)!)*sqrt(pi) // also 2n-1 is the numerator @@ -2196,6 +2236,10 @@ protected override Entity InnerSimplify(bool isExact) Real nan when nan.EDecimal.IsNaN() => nan, Real n => n.EDecimal.Sign, Complex n when !isExact => Number.Signum(n), + // A constant whose parts decide its sign has it, however far past the decimals' range it is: + // e^400000 evaluates to +oo, which is no value to take, and its sign is still 1. + // https://github.com/asc-community/AngouriMath/issues/2753 + _ when isExact && SignOfANonzero(a) is { } sign => Integer.Create(sign), // sgn(|z|) is 1 wherever z is nonzero and 0 where it is not: |z| is never // negative, so the only question is whether it vanishes. This answered 1 // for every argument -- so sgn(abs(x)) simplified to 1, where at x = 0 the @@ -2237,6 +2281,12 @@ protected override Entity InnerSimplify(bool isExact) // floor(10^120 - 1/3) came out 10^120. // https://github.com/asc-community/AngouriMath/issues/1807 Rational n => Integer.Create(RoundedQuotient(n.ERational, up: false)), + // A nonzero real below 1 in magnitude, as its parts prove it, and not as its decimal reads: + // e^(-400000) flushes to 0, and its floor is 0 by its sign and bound, not by that. + // https://github.com/asc-community/AngouriMath/issues/2753 + _ when SignWithMagnitudeBelow(a, Integer.One) is { } side => side > 0 ? Integer.Zero : Integer.MinusOne, + // At the boundary the decimal cannot tell, from an enclosure. https://github.com/asc-community/AngouriMath/issues/2775 + _ when isExact && a.IsConstant && IntegerPartByEnclosure(a) is { } whole => whole, Real n when !isExact => Integer.Create(n.EDecimal.Floor().ToEInteger()), Complex n when !isExact => Complex.Create( n.RealPart.EDecimal.Floor(), n.ImaginaryPart.EDecimal.Floor()), @@ -2292,6 +2342,10 @@ protected override Entity InnerSimplify(bool isExact) // As in Floorf: https://github.com/asc-community/AngouriMath/issues/830 Real { IsFinite: false } n => n, Rational n => Integer.Create(RoundedQuotient(n.ERational, up: true)), + // As in Floorf. https://github.com/asc-community/AngouriMath/issues/2753 + _ when SignWithMagnitudeBelow(a, Integer.One) is { } side => side > 0 ? Integer.One : Integer.Zero, + // At the boundary the decimal cannot tell, from an enclosure. https://github.com/asc-community/AngouriMath/issues/2775 + _ when isExact && a.IsConstant && IntegerPartByEnclosure(a) is { } whole => Integer.Create(whole.EInteger + PeterO.Numbers.EInteger.One), Real n when !isExact => Integer.Create(n.EDecimal.Ceiling().ToEInteger()), Complex n when !isExact => Complex.Create( n.RealPart.EDecimal.Ceiling(), n.ImaginaryPart.EDecimal.Ceiling()), @@ -2319,6 +2373,10 @@ protected override Entity InnerSimplify(bool isExact) // https://github.com/asc-community/AngouriMath/issues/2282 Real { IsFinite: false } n => n, Rational n => Integer.Create(RoundedHalfEven(n.ERational)), + // Below a half in magnitude, as its parts prove it. https://github.com/asc-community/AngouriMath/issues/2753 + _ when SignWithMagnitudeBelow(a, Rational.Create(1, 2)) is not null => Integer.Zero, + // At the boundary the decimal cannot tell, from an enclosure. https://github.com/asc-community/AngouriMath/issues/2775 + _ when isExact && a.IsConstant && IntegerPartByEnclosure(a + Rational.Create(1, 2)) is { } whole => whole, Real n when !isExact => Integer.Create(n.EDecimal.RoundHalfEven().ToEInteger()), Complex n when !isExact => Complex.Create( n.RealPart.EDecimal.RoundHalfEven(), n.ImaginaryPart.EDecimal.RoundHalfEven()), diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Trigonometry.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Trigonometry.Classes.cs index 6395a3129..360280b50 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Trigonometry.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Trigonometry.Classes.cs @@ -17,7 +17,8 @@ internal static bool IsSinDefinitelyZero(Entity angle) angle.Complexity < 100 // is it of the form n * pi? - && MathS.UnsafeAndInternal.DivideByEntityStrict(angle, MathS.pi)?.Evaled is Integer; + && MathS.UnsafeAndInternal.DivideByEntityStrict(angle, MathS.pi) is { Evaled: Integer } turns + && !Entity.RestsOnARounding(turns); internal static bool IsCosDefinitelyZero(Entity angle) => @@ -25,7 +26,8 @@ internal static bool IsCosDefinitelyZero(Entity angle) angle.Complexity < 100 // is it of the form n / m * pi? - && MathS.UnsafeAndInternal.DivideByEntityStrict(angle, MathS.pi)?.Evaled is Rational angleRat + && MathS.UnsafeAndInternal.DivideByEntityStrict(angle, MathS.pi) is { Evaled: Rational angleRat } turns + && !Entity.RestsOnARounding(turns) // if n / m is integer + 1/2 @@ -38,6 +40,26 @@ internal static bool IsCosDefinitelyZero(Entity angle) partial record Entity { + /// + /// Whether , read off a table of the function for an angle the + /// evaluation of agrees with to the working digits, is its value at the argument. An + /// argument written as a rational number of half turns is the table's angle exactly; any other is held to an + /// enclosure, since one nearer the angle than the working digits reach was read as it: sin(1/10^99) and + /// sin(pi + 1/10^150) were 0. https://github.com/asc-community/AngouriMath/issues/2775 + /// + private static bool TableValueHolds(System.Func function, Entity argument, Entity value) + => argument is Integer { IsZero: true } + || MathS.UnsafeAndInternal.DivideByEntityStrict(argument, MathS.pi) is { } turns && IsRationalArithmetic(turns) + || !IsShownNotToBe(function(argument), value); + + /// + /// for the inverse functions, whose tables are read by the argument: a rational one + /// was compared exactly by the table, and any other is held to an enclosure, as arctan(e^(-1000)) is not 0. + /// https://github.com/asc-community/AngouriMath/issues/2775 + /// + private static bool InverseTableValueHolds(System.Func function, Entity argument, Entity value) + => argument.Evaled is Rational || !IsShownNotToBe(function(argument), value); + public partial record Sinf { private protected override Entity IntrinsicCondition => Boolean.True; @@ -47,7 +69,7 @@ protected override Entity InnerSimplify(bool isExact) => a => a switch { Complex n when !isExact => Number.Sin(n), - { Evaled: Complex n } arg when isExact && TrigonometryTableValues.PullSin(n, out var res) => res, + { Evaled: Complex n } arg when isExact && !RestsOnARounding(arg) && TrigonometryTableValues.PullSin(n, out var res) && TableValueHolds(static x => new Sinf(x), arg, res) => res, _ when Functions.Boolean.QuantifierFacts.WithoutWholePeriods(a, 2, static x => new Sinf(x), "Complex.sin_add_int_mul_two_pi") is { } reduced => reduced.InnerSimplified(isExact), _ => null }, @@ -63,7 +85,7 @@ protected override Entity InnerSimplify(bool isExact) => a => a switch { Complex n when !isExact => Number.Cos(n), - { Evaled: Complex n } when isExact && TrigonometryTableValues.PullCos(n, out var res) => res, + { Evaled: Complex n } when isExact && !RestsOnARounding(a) && TrigonometryTableValues.PullCos(n, out var res) && TableValueHolds(static x => new Cosf(x), a, res) => res, _ when Functions.Boolean.QuantifierFacts.WithoutWholePeriods(a, 2, static x => new Cosf(x), "Complex.cos_add_int_mul_two_pi") is { } reduced => reduced.InnerSimplified(isExact), _ => null }, @@ -79,9 +101,9 @@ protected override Entity InnerSimplify(bool isExact) => : ExpandOnOneArgument(Argument, a => a switch { - { Evaled: Complex n } => + { Evaled: Complex n } when !isExact || !RestsOnARounding(a) => isExact - ? TrigonometryTableValues.PullCos(n, out var res) + ? TrigonometryTableValues.PullCos(n, out var res) && TableValueHolds(static x => new Cosf(x), a, res) ? (1 / res).InnerSimplified : null : Secant(n), @@ -100,9 +122,9 @@ protected override Entity InnerSimplify(bool isExact) => : ExpandOnOneArgument(Argument, a => a switch { - { Evaled: Complex n } => + { Evaled: Complex n } when !isExact || !RestsOnARounding(a) => isExact - ? TrigonometryTableValues.PullSin(n, out var res) + ? TrigonometryTableValues.PullSin(n, out var res) && TableValueHolds(static x => new Sinf(x), a, res) ? (1 / res).InnerSimplified : null : Cosecant(n), @@ -157,9 +179,9 @@ protected override Entity InnerSimplify(bool isExact) => : ExpandOnOneArgument(Argument, a => a switch { - { Evaled: Complex n } => + { Evaled: Complex n } when !isExact || !RestsOnARounding(a) => isExact - ? TrigonometryTableValues.PullTan(n, out var res) ? res : null + ? TrigonometryTableValues.PullTan(n, out var res) && TableValueHolds(static x => new Tanf(x), a, res) ? res : null : Number.Tan(n), _ when Functions.Boolean.QuantifierFacts.WithoutWholePeriods(a, 1, static x => new Tanf(x), "Complex.tan_add_int_mul_pi") is { } reduced => reduced.InnerSimplified(isExact), _ => null @@ -176,9 +198,9 @@ protected override Entity InnerSimplify(bool isExact) => : ExpandOnOneArgument(Argument, a => a switch { - { Evaled: Complex n } => + { Evaled: Complex n } when !isExact || !RestsOnARounding(a) => isExact - ? TrigonometryTableValues.PullTan(n, out var res) ? (1 / res).InnerSimplified : null + ? TrigonometryTableValues.PullTan(n, out var res) && TableValueHolds(static x => new Tanf(x), a, res) ? (1 / res).InnerSimplified : null : Number.Cotan(n), _ when Functions.Boolean.QuantifierFacts.WithoutWholePeriods(a, 1, static x => new Cotanf(x), "Complex.tan_add_int_mul_pi") is { } reduced => reduced.InnerSimplified(isExact), _ => null @@ -198,7 +220,7 @@ protected override Entity InnerSimplify(bool isExact) => a => a switch { Complex n when !isExact => Number.Arcsin(n), - { Evaled: Complex n } when isExact && InverseTrigonometricTableValues.PullArcsin(n, out var res) => res, + { Evaled: Complex n } when isExact && !RestsOnARounding(a) && InverseTrigonometricTableValues.PullArcsin(n, out var res) && InverseTableValueHolds(static x => new Arcsinf(x), a, res) => res, // Increasing on [-1; 1]. https://github.com/asc-community/AngouriMath/issues/322 Set.Interval interval when IntervalArithmetic.MonotoneOn(interval, -1, 1, increasing: true, MathS.Arcsin, isExact) is { } image => image, _ => null @@ -218,7 +240,7 @@ protected override Entity InnerSimplify(bool isExact) => a => a switch { Complex n when !isExact => Number.Arccos(n), - { Evaled: Complex n } when isExact && InverseTrigonometricTableValues.PullArccos(n, out var res) => res, + { Evaled: Complex n } when isExact && !RestsOnARounding(a) && InverseTrigonometricTableValues.PullArccos(n, out var res) && InverseTableValueHolds(static x => new Arccosf(x), a, res) => res, // Decreasing on [-1; 1]. https://github.com/asc-community/AngouriMath/issues/322 Set.Interval interval when IntervalArithmetic.MonotoneOn(interval, -1, 1, increasing: false, MathS.Arccos, isExact) is { } image => image, _ => null @@ -248,7 +270,7 @@ Real r when r.EDecimal.IsNegativeInfinity() => -MathS.pi / 2, // pi/4 stopped one step short of it. Integer(1) => MathS.pi / 4, Integer(-1) => -MathS.pi / 4, - { Evaled: Complex n } when isExact && InverseTrigonometricTableValues.PullArctan(n, out var res) => res, + { Evaled: Complex n } when isExact && !RestsOnARounding(a) && InverseTrigonometricTableValues.PullArctan(n, out var res) && InverseTableValueHolds(static x => new Arctanf(x), a, res) => res, // Increasing everywhere. https://github.com/asc-community/AngouriMath/issues/322 Set.Interval interval when IntervalArithmetic.Monotone(interval, increasing: true, MathS.Arctan, isExact) is { } image => image, _ => null @@ -268,7 +290,7 @@ protected override Entity InnerSimplify(bool isExact) => a => a switch { Complex n when !isExact => Number.Arccotan(n), - { Evaled: Complex n } when isExact && InverseTrigonometricTableValues.PullArccotan(n, out var res) => res, + { Evaled: Complex n } when isExact && !RestsOnARounding(a) && InverseTrigonometricTableValues.PullArccotan(n, out var res) && InverseTableValueHolds(static x => new Arccotanf(x), a, res) => res, _ => null }, (@this, a) => ((Arccotanf)@this).New(a), isExact); diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs index 07ea2739a..04826d76b 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs @@ -332,7 +332,13 @@ protected override Entity InnerSimplify(bool isExact) // told apart from a number or another such power where its sign, exponent or magnitude decides it. // https://github.com/asc-community/AngouriMath/issues/1448 : OrderOfUnbuiltPowers(left, right) is { } order ? order == 0 - : left.IsConstant && right.IsConstant ? (HasAnUnreadSize(left) || HasAnUnreadSize(right) ? null : ConstantsAreEqual(left, right)) + // Nor is a side whose value the decimals' exponent range made: e^(-400000) = 0 was True, the + // left side flushed to 0. https://github.com/asc-community/AngouriMath/issues/2753 + : left.IsConstant && right.IsConstant ? (HasAnUnreadSize(left) || HasAnUnreadSize(right) ? null + // A side that only rounding made the value it evaluates to is told from the other by enclosures, + // or not at all: 1 - e^(-200) = 1 was True. https://github.com/asc-community/AngouriMath/issues/2775 + : RestsOnARounding(left) || RestsOnARounding(right) ? (IsShownNotToBe(left, right) ? false : null) + : ConstantsAreEqual(left, right)) : left is Set setLeft && right is Set setRight ? SetsAreEqual(setLeft, setRight, isExact) : null, (@this, a, b) => ((Equalsf)@this).New(a, b), isExact, @@ -367,6 +373,10 @@ protected override Entity InnerSimplify(bool isExact) // First, since a flushed value comes back as the exact 0. if (IsFlushedOrSaturated(leftWritten, left) || IsFlushedOrSaturated(rightWritten, right)) return null; + // A side whose value only rounding made is ordered by enclosures, or not at all: cos(1/10^30) < 1 was False, + // the cosine evaluating to 1. https://github.com/asc-community/AngouriMath/issues/2775 + if (RestsOnARounding(leftWritten) || RestsOnARounding(rightWritten)) + return OrderByEnclosures(leftWritten, rightWritten); if (left is Number.Rational { ERational: var exactLeft } && right is Number.Rational { ERational: var exactRight }) return exactLeft.CompareTo(exactRight); var (a, b) = (left.EDecimal, right.EDecimal); @@ -534,6 +544,8 @@ protected override Entity InnerSimplify(bool isExact) (Number numLeft, Number numRight) => MathS.NaN, _ when AngouriMath.Core.Sets.Cardinality.IsSize(a) || AngouriMath.Core.Sets.Cardinality.IsSize(b) => AngouriMath.Core.Sets.Cardinality.Compare(a, b, static sign => sign > 0, isExact), _ when OrderOfUnbuiltPowers(a, b) is { } sign => sign > 0, + // See Ordered: a side only rounding made a number stays written. https://github.com/asc-community/AngouriMath/issues/2775 + _ when a.IsConstant && b.IsConstant && (RestsOnARounding(a) || RestsOnARounding(b)) && OrderByEnclosures(a, b) is { } sign => sign > 0, _ => null }, (@this, a, b) => ((Greaterf)@this).New(a, b), isExact); @@ -556,6 +568,8 @@ protected override Entity InnerSimplify(bool isExact) (Number numLeft, Number numRight) => MathS.NaN, _ when AngouriMath.Core.Sets.Cardinality.IsSize(a) || AngouriMath.Core.Sets.Cardinality.IsSize(b) => AngouriMath.Core.Sets.Cardinality.Compare(a, b, static sign => sign >= 0, isExact), _ when OrderOfUnbuiltPowers(a, b) is { } sign => sign >= 0, + // See Ordered: a side only rounding made a number stays written. https://github.com/asc-community/AngouriMath/issues/2775 + _ when a.IsConstant && b.IsConstant && (RestsOnARounding(a) || RestsOnARounding(b)) && OrderByEnclosures(a, b) is { } sign => sign >= 0, _ => null }, (@this, a, b) => ((GreaterOrEqualf)@this).New(a, b), isExact); @@ -578,6 +592,8 @@ protected override Entity InnerSimplify(bool isExact) (Number numLeft, Number numRight) => MathS.NaN, _ when AngouriMath.Core.Sets.Cardinality.IsSize(a) || AngouriMath.Core.Sets.Cardinality.IsSize(b) => AngouriMath.Core.Sets.Cardinality.Compare(a, b, static sign => sign < 0, isExact), _ when OrderOfUnbuiltPowers(a, b) is { } sign => sign < 0, + // See Ordered: a side only rounding made a number stays written. https://github.com/asc-community/AngouriMath/issues/2775 + _ when a.IsConstant && b.IsConstant && (RestsOnARounding(a) || RestsOnARounding(b)) && OrderByEnclosures(a, b) is { } sign => sign < 0, _ => null }, (@this, a, b) => ((Lessf)@this).New(a, b), isExact); @@ -599,6 +615,8 @@ protected override Entity InnerSimplify(bool isExact) (Number numLeft, Number numRight) => MathS.NaN, _ when AngouriMath.Core.Sets.Cardinality.IsSize(a) || AngouriMath.Core.Sets.Cardinality.IsSize(b) => AngouriMath.Core.Sets.Cardinality.Compare(a, b, static sign => sign <= 0, isExact), _ when OrderOfUnbuiltPowers(a, b) is { } sign => sign <= 0, + // See Ordered: a side only rounding made a number stays written. https://github.com/asc-community/AngouriMath/issues/2775 + _ when a.IsConstant && b.IsConstant && (RestsOnARounding(a) || RestsOnARounding(b)) && OrderByEnclosures(a, b) is { } sign => sign <= 0, _ => null }, (@this, a, b) => ((LessOrEqualf)@this).New(a, b), isExact); diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs index 0d9b42bc5..5dca7d192 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs @@ -452,7 +452,9 @@ private Entity Decide(Entity expr, Entity predicate) { if (predicate.Evaled == Boolean.True) return expr; - if (predicate.Evaled == Boolean.False || predicate.Evaled.IsNaN) + // A NaN only the working digits made is no answer: not sin(e^1000) = 0 evaluates to NaN, as sin(e^1000) + // does, and holds. https://github.com/asc-community/AngouriMath/issues/2775 + if (predicate.Evaled == Boolean.False || predicate.Evaled.IsNaN && !IsANaNOnlyLostDigitsMade(predicate, predicate.Evaled)) return MathS.NaN; return New(expr, predicate); } diff --git a/Sources/AngouriMath/Functions/Simplification/InverseTrigonometricTableValues.cs b/Sources/AngouriMath/Functions/Simplification/InverseTrigonometricTableValues.cs index a2e86736f..95e2ff19d 100644 --- a/Sources/AngouriMath/Functions/Simplification/InverseTrigonometricTableValues.cs +++ b/Sources/AngouriMath/Functions/Simplification/InverseTrigonometricTableValues.cs @@ -155,9 +155,18 @@ private static bool TryPull(List<(double approximation, Entity value, Entity ang // Near a table value is not the same as being one: 0.4999999 must come back // unanswered rather than as pi/6, so the sieve hit is checked against the exact // value at the precision the caller asked for. - if (value.Evaled is not Real { EDecimal: var exact }) + if (value.Evaled is not Real { EDecimal: var exact } exactValue) return false; - if (!TrigonometryTableValues.AgreesToTheWorkingDigits(exact, negative ? given.Negate() : given, exact.Abs().Add(EDecimal.One))) + // A rational argument is a rational entry exactly or not at all, and never an irrational one: arctan of + // 1/10^150 agreed with the entry 0 to the working digits, and was 0. + // https://github.com/asc-community/AngouriMath/issues/2775 + if (arg is Rational || exactValue is Rational) + { + if (arg is not Rational { ERational: var argument } || exactValue is not Rational { ERational: var entry } + || argument.Abs().CompareTo(entry) != 0) + return false; + } + else if (!TrigonometryTableValues.AgreesToTheWorkingDigits(exact, negative ? given.Negate() : given, exact.Abs().Add(EDecimal.One))) return false; // Both functions in the table are odd, so a negative argument is the same angle // the other way round. diff --git a/Sources/Tests/UnitTests/Common/NearIntegerConstantsStayWrittenTest.cs b/Sources/Tests/UnitTests/Common/NearIntegerConstantsStayWrittenTest.cs new file mode 100644 index 000000000..2b8ae48bf --- /dev/null +++ b/Sources/Tests/UnitTests/Common/NearIntegerConstantsStayWrittenTest.cs @@ -0,0 +1,124 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using AngouriMath.Extensions; +using PeterO.Numbers; +using Xunit; +using static AngouriMath.Entity; + +namespace AngouriMath.Tests.Common +{ + /// + /// Evaluation rounds a value within 1e-50 of a small rational onto it, and Simplify took that rational for the + /// value of a constant that is only near it: 1 - e^(-200) was 1, sin(1/10^99) 0, and tan(e^1000), + /// whose argument the working digits cannot place within its period, NaN. + /// https://github.com/asc-community/AngouriMath/issues/2775 + /// + [Trait("Area", "Common")] + public sealed class NearIntegerConstantsStayWrittenTest + { + /// + /// The answer is not a number, and in a thousand digits it is on the side of the constant + /// is: the values are 1e-50 to 1e-348 from it. + /// + [Theory] + [InlineData("1 - e^(-200)", "1", -1)] + [InlineData("1 + e^(-150)", "1", 1)] + [InlineData("sinh(60)/cosh(60)", "1", -1)] + [InlineData("sinh(400)/cosh(400)", "1", -1)] + [InlineData("(e^200 - 1)/e^200", "1", -1)] + [InlineData("sqrt(10^120 + 1) / 10^60", "1", 1)] + [InlineData("sqrt(10^120 - 1) / 10^60", "1", -1)] + [InlineData("1/3 + e^(-200)", "1/3", 1)] + [InlineData("(1 + e^(-200)) - 1", "0", 1)] + [InlineData("cos(1/10^60)", "1", -1)] + [InlineData("ln(1 + e^(-200))", "0", 1)] + [InlineData("sin(1/10^99)", "0", 1)] + [InlineData("tan(1/10^150)", "0", 1)] + [InlineData("arctan(1/10^150)", "0", 1)] + [InlineData("arcsin(1/10^150)", "0", 1)] + [InlineData("arctan(e^(-276))", "0", 1)] + [InlineData("sin(pi + 1/10^150)", "0", -1)] + [InlineData("sin(e^(-1000))", "0", 1)] + [InlineData("sin(pi/6 + 1/10^90)", "1/2", 1)] + [InlineData("tan(pi/4 + 1/10^90)", "1", 1)] + [InlineData("(-e^(-1000)) mod 1", "1", -1)] + [InlineData("(7/2 - e^(-200)) mod 1", "1/2", -1)] + [InlineData("(1 + e^(-200)) mod 1", "0", 1)] + [InlineData("(5 - e^(-200)) mod 2", "1", -1)] + public void TheConstantIsNotTheRationalNearIt(string expression, string near, int side) + { + var simplified = expression.ToEntity().Simplify(); + Assert.False(simplified is Number, $"{expression} simplified to the number {simplified}"); + using var _ = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(1000)); + var difference = (simplified - near.ToEntity()).EvalNumerical(); + Assert.True(difference is Number.Real real && real.EDecimal.Sign == side, $"{expression} - {near} is {difference}"); + } + + /// + /// A trigonometric function of an argument the working digits cannot place within its period has a value all the + /// same, and is left written rather than NaN. + /// + [Theory] + [InlineData("tan(e^1000)")] + [InlineData("cot(e^1000)")] + [InlineData("sec(e^1000)")] + [InlineData("csc(e^1000)")] + [InlineData("1/cos(e^1000) + x")] + public void ALargeArgumentIsNotNaN(string expression) + => Assert.False(expression.ToEntity().Simplify().IsNaN, $"{expression} simplified to NaN"); + + /// + /// The identity holds where the sine is not 0, which an enclosure in more digits shows, rather than its provision + /// being taken for false. + /// + [Fact] + public void AnIdentityAtALargeArgumentHolds() + => Assert.Equal(Number.Integer.One, "csc(e^1000)^2 - cot(e^1000)^2".ToEntity().Simplify()); + + /// Constants that are the rational, written irrationally, still simplify to it. + [Theory] + [InlineData("sqrt(10^120) / 10^60", "1")] + [InlineData("cosh(1)^2 - sinh(1)^2", "1")] + [InlineData("cosh(200)^2 - sinh(200)^2", "1")] + [InlineData("e^(ln(3))", "3")] + [InlineData("sqrt(2)^2", "2")] + [InlineData("(sqrt(3) + 1) * (sqrt(3) - 1)", "2")] + [InlineData("sqrt(8) - 2 * sqrt(2)", "0")] + [InlineData("sin(pi)", "0")] + [InlineData("sin(pi/6)", "1/2")] + [InlineData("arcsin(1/2)", "pi/6")] + [InlineData("arctan(sqrt(3))", "pi/3")] + [InlineData("tan(pi/12)", "2 - sqrt(3)")] + public void ARationalWrittenIrrationallyIsStillIt(string expression, string expected) + => Assert.Equal(expected.ToEntity().InnerSimplified, expression.ToEntity().Simplify()); + + /// A floor, a ceiling and a rounding at the integer or the half the argument is near are decided by its value. + [Theory] + [InlineData("floor(1 - e^(-200))", 0)] + [InlineData("floor(cos(1/10^60))", 0)] + [InlineData("ceil(1 + e^(-200))", 2)] + [InlineData("ceil(sqrt(10^120 + 1) / 10^60)", 2)] + [InlineData("round(1/2 + e^(-200))", 1)] + [InlineData("round(1/2 - e^(-200))", 0)] + [InlineData("floor(sqrt(2))", 1)] + [InlineData("ceil(pi)", 4)] + public void AnIntegerPartAtItsBoundaryIsDecidedByTheValue(string expression, int expected) + => Assert.Equal(Number.Integer.Create(expected), expression.ToEntity().Simplify()); + + /// An equality or an order of such a constant and the rational is decided by their values. + [Theory] + [InlineData("1 - e^(-200) = 1", false)] + [InlineData("1 - e^(-200) < 1", true)] + [InlineData("1 + e^(-200) <= 1", false)] + [InlineData("cos(1/10^30) < 1", true)] + [InlineData("cos(1/10^30) >= 1", false)] + [InlineData("cosh(3)^2 - sinh(3)^2 = 1", true)] + public void AComparisonIsDecidedByTheValues(string expression, bool expected) + => Assert.Equal((Entity)expected, expression.ToEntity().Simplify()); + } +} diff --git a/Sources/Tests/UnitTests/Common/ValuesPastTheExponentRangeStayExactTest.cs b/Sources/Tests/UnitTests/Common/ValuesPastTheExponentRangeStayExactTest.cs new file mode 100644 index 000000000..60df2a3ef --- /dev/null +++ b/Sources/Tests/UnitTests/Common/ValuesPastTheExponentRangeStayExactTest.cs @@ -0,0 +1,114 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using AngouriMath.Extensions; +using Xunit; +using static AngouriMath.Entity; + +namespace AngouriMath.Tests.Common +{ + /// + /// A value past the decimals' exponent range evaluates to +oo or flushes to 0, and Simplify took those + /// for the exact values of the nodes: exp(400000) * exp(-399999) was 0 and e^400000 / e^399999 was + /// NaN, where both are e. + /// https://github.com/asc-community/AngouriMath/issues/2753 + /// + [Trait("Area", "Common")] + public sealed class ValuesPastTheExponentRangeStayExactTest + { + [Theory] + [InlineData("exp(400000) * exp(-399999)", "e")] + [InlineData("e^400000 / e^399999", "e")] + [InlineData("exp(10^6) / exp(10^6 - 1)", "e")] + [InlineData("exp(-250000) / exp(-250001)", "e")] + [InlineData("e^400000 / e^400000", "1")] + [InlineData("gamma(300000.5) / gamma(299999.5)", "599999/2")] + [InlineData("gamma(600001/2) / gamma(600007/2)", "8/216003240013800015")] + [InlineData("(-1/2)! / (-3/2)!", "-1/2")] + public void TheQuotientIsItsExactValue(string expression, string expected) + => Assert.Equal(expected.ToEntity().InnerSimplified, expression.ToEntity().Simplify()); + + /// + /// Neither 0, nor an infinity, nor NaN, nor any number: each is a finite nonzero value that no exact number + /// short of the expression itself writes. + /// + [Theory] + [InlineData("exp(-400000)")] + [InlineData("exp(-400000) + 1")] + [InlineData("exp(-400000) * x")] + [InlineData("1 / (e^400000 + 1)")] + [InlineData("exp(-250000) * 10^100000")] + [InlineData("sinh(400000) / cosh(400000)")] + [InlineData("sin(e^400000)")] + [InlineData("sin(e^(-400000))")] + [InlineData("cos(e^(-400000))")] + [InlineData("tan(e^(-400000))")] + [InlineData("csc(e^(-400000))")] + [InlineData("arcsin(e^(-400000))")] + [InlineData("abs(e^400000)")] + [InlineData("abs(e^(-400000))")] + [InlineData("floor(e^400000)")] + [InlineData("gamma(e^400000)")] + public void TheValueIsNotTakenFromTheDecimals(string expression) + { + var simplified = expression.ToEntity().Simplify(); + Assert.False(simplified is Number, $"{expression} simplified to the number {simplified}"); + Assert.False(simplified.IsNaN, $"{expression} simplified to NaN"); + } + + /// A flushed side is not 0, and two saturated sides are not equal. + [Theory] + [InlineData("e^(-400000) = 0")] + [InlineData("e^400000 = e^400001")] + public void AnEqualityIsNotDecidedTrueByTheDecimals(string expression) + => Assert.NotEqual(Boolean.True, expression.ToEntity().Simplify()); + + /// The sign of such a value is still the sign its parts decide. + [Theory] + [InlineData("sgn(e^400000)", 1)] + [InlineData("sgn(e^(-400000))", 1)] + [InlineData("sgn(-e^400000)", -1)] + [InlineData("sgn(-1 / e^400000)", -1)] + public void TheSignIsKept(string expression, int sign) + => Assert.Equal(Number.Integer.Create(sign), expression.ToEntity().Simplify()); + + /// + /// The whole numbers around such a value are read from its sign and a bound its parts prove, never from the + /// decimal it flushed to: e^(-400000) is in (0, 1), and its floor is 0 and its ceiling 1. + /// + [Theory] + [InlineData("floor(e^(-400000))", "0")] + [InlineData("floor(1 / e^400000)", "0")] + [InlineData("floor(-e^(-400000))", "-1")] + [InlineData("floor(3 / e^400000)", "0")] + [InlineData("floor(pi / e^400000)", "0")] + [InlineData("floor(e^(-400000) * sqrt(2))", "0")] + [InlineData("ceil(e^(-400000))", "1")] + [InlineData("ceil(-e^(-400000))", "0")] + [InlineData("ceil(-pi / e^400000)", "0")] + [InlineData("ceil(5 * 2^(-400000))", "1")] + [InlineData("round(e^(-400000))", "0")] + [InlineData("round(10^99 / e^400000)", "0")] + [InlineData("e^(-400000) mod 1", "1 / e^400000")] + [InlineData("(-e^(-400000)) mod 1", "1 - 1 / e^400000")] + [InlineData("e^(-1000) mod 1", "1 / e^1000")] + [InlineData("floor(8 / e^2)", "1")] + [InlineData("floor(3 / e^2)", "0")] + public void TheRoundingIsReadFromTheBound(string expression, string expected) + { + var simplified = expression.ToEntity().Simplify(); + Assert.Equal(Number.Integer.Zero, (simplified - expected.ToEntity()).Simplify()); + } + + /// A quotient of factorials too large to write out is still read exactly, and within reach as before. + [Theory] + [InlineData("gamma(20001/2) / gamma(19999/2)", "19999/2")] + [InlineData("5! / 3!", "20")] + public void AFactorialQuotientWithinReachIsUnchanged(string expression, string expected) + => Assert.Equal(expected.ToEntity().InnerSimplified, expression.ToEntity().Simplify()); + } +}