diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 9d3e6e7b8..a3f2bc4d8 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -503,6 +503,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/Evaluation/Evaluation.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs index ce39238e8..1e3da9b8e 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs @@ -53,32 +53,183 @@ 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); + + /// + /// 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 +244,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 +297,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 +312,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 +388,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 +411,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 +666,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 +677,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 +698,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 +710,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..03ea3aa93 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,10 @@ 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, // 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 +1328,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 +1356,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 +2232,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 +2277,10 @@ 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, 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 +2336,8 @@ 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, 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 +2365,8 @@ 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, 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..ed8c7b1d9 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 @@ -47,7 +49,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) => 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 +65,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) => 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,7 +81,7 @@ 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) ? (1 / res).InnerSimplified @@ -100,7 +102,7 @@ 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) ? (1 / res).InnerSimplified @@ -157,7 +159,7 @@ 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 : Number.Tan(n), @@ -176,7 +178,7 @@ 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 : Number.Cotan(n), @@ -198,7 +200,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) => 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 +220,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) => 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 +250,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) => 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 +270,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) => 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..7f977087a 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,9 @@ 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) || RestsOnARounding(left) || RestsOnARounding(right) ? 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, 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()); + } +}