From 0e9fc5347ae0180356f5e2a139b79cb169d8417b Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Fri, 4 Dec 2026 11:39:04 +0000 Subject: [PATCH] Keep the small parts of tanh, coth, sech and csch off the real line, and every digit of a small quotient tanh and coth are spelled (e^(2 z) - 1)/(e^(2 z) + 1) and its reciprocal, and sech and csch as reciprocals of (e^z +- e^(-z))/2. Evaluated as written, a part small beside the two powers cancelled in the quotient or the sum: tanh(10^(-60) + i) lost its real part 3.4E-60, coth likewise, and sech(10^(-60) + i) its imaginary part. Off the real line each spelling is now evaluated as the trigonometric function of i z: tanh z = -i tan(i z), coth z = i cot(i z), cosh z = cos(i z), sinh z = -i sin(i z), whose parts cancel nothing but a residual of a multiple of pi/2. A real exponent keeps the spelling. e^u - 1 read both parts against one scale, |e^v| (|e^d| + 1), so the imaginary part of e^(-200 + 2 i) - 1, which cancels nothing, was read against the 1 and dropped; tanh(-100 + i) takes it once from each side of its quotient and had half its imaginary part. Each part is now read against what it is a sum of. tan off the real line took its denominator as cos 2x + cosh 2y, itself a residual near a pole, so tan(pi/2 + 10^(-60) i), 10^60 i, was -oo + oo i; it is now cos^2 x + sinh^2 y, and tan and cot read a sine or a cosine that is a residual of x as 0, as sin and cos do: the real part of cot(pi + 10^(-30) i) was 1.8E-41. A real tangent whose cosine is a residual is NaN, as at an exact pole. A quotient was divided to a hundred decimal places and divided again to digits only below 285 bits, so one below 0.1 kept as few as 86 digits; sec(1/2 - 30 i), the reciprocal of a cosine near 5e12, kept 88. One that is surely below 0.1, from the two sides' exponents and bits, is now divided to as many more places as it has zeros after the point and rounded to the digits, and the second division is made below all but one of the working digits. tan within |y| <= 4 is taken with ten guard digits, and the pinned last digit of the real part of tan(3 +- 2 i) is now the correctly rounded one. tanh(100 + i) keeps its imaginary part 2.5E-87, below 1e-50 of its modulus: it is no residual, and tanh(-100 + i) keeps it. Fixes #2701 Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 41 +++++++ .../Entity/Continuous/Number/Operators.cs | 109 ++++++++++++------ ...aluation.Continuous.Arithmetics.Classes.cs | 5 + .../Functions/ExponentialQuotients.cs | 69 +++++++++++ .../Common/NumericsRegressionTest.cs | 39 +++++++ Sources/Tests/UnitTests/Core/NumericDigits.cs | 4 +- 6 files changed, 230 insertions(+), 37 deletions(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 67e7a9ab4..f4a8bb9b1 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -354,6 +354,47 @@ Of 8400 values of `cos`, `sin`, `tan`, `sec`, `csc`, `cot`, `cosh`, `sinh`, `tan 16 imaginary parts of `tanh` are now right, and of the rows right on master only the last digit of `sinh(10^4 ± pi/4 i)` moved. +### tanh, coth, sech and csch off the real line, and a reciprocal near 1e-13, keep their small parts and digits + +**Silent: wrong numbers become right ones.** `tanh` and `coth` are spelled `(e^(2 z) ∓ 1)/(e^(2 z) ± 1)`, and `sech` +and `csch` as reciprocals of `(e^z ± e^(-z))/2`. Evaluated as written, a part small beside the two powers cancelled in +the quotient or the sum and was dropped, and `e^(2 z) - 1` read its imaginary part against the 1, so `tanh(-100 + i)` +had half its imaginary part. Off the real line each is now taken as the trigonometric function of `i z`, `tanh z` as +`-i tan(i z)`, whose parts cancel nothing but a residual of a multiple of `pi/2`, and `e^u - 1` reads each part +against what it is a sum of. `tan` and `cot` off the real line now read a sine or a cosine that is a residual of the +real part as 0, as `sin` and `cos` do, and `tan`'s denominator is `cos^2 x + sinh^2 y` where it was +`cos 2x + cosh 2y`, a residual itself near a pole. A real quotient below 0.1 was divided to a hundred decimal places +and kept down to 86 digits, so `sec(1/2 - 30 i)`, the reciprocal of a cosine near `5e12`, kept 88; it keeps 99. +`tanh(100 + i)`, which has the imaginary part `2.5E-87`, below `1e-50` of its modulus, was 1 and now keeps it, as +`tanh(-100 + i)` does: the part is no residual, and `tanh` is odd. Measured on master (0ce20c5a8) and on this +branch; the true values are mpmath's at 450 and 1000 digits ([#2701](https://github.com/asc-community/AngouriMath/issues/2701)). + +| `.Evaled` | Was (master) | Now | +|---|---|---| +| `tanh(10^(-60) + i)` | `1.557407…i` | `3.425518…E-60 + 1.557407…i` | +| `coth(10^(-60) + i)` | `-0.642092…i` | `1.412282…E-60 - 0.642092…i` | +| `tanh(-100 + i)` | `-1 + 1.258373…E-87i` | `-1 + 2.516747…E-87i` | +| `tanh(-100 + 1/3 * i)` | `-1 + 8.557598…E-88i` | `-1 + 1.711519…E-87i` | +| `tanh(100 + i)` | `1` | `1 + 2.516747…E-87i` | +| `sech(10^(-60) + i)` | `1.850815…` | `1.850815… - 2.882474…E-60i` | +| `tanh(10^(-60) * i)` | `1E-120 + 1E-60i` | `1E-60i` | +| `tanh(10^(-60) + pi/2 * i)` | `NaN` | `1E+60` | +| `tan(pi/2 + 10^(-60) * i)` | `-oo + +ooi` | `1E+60i` | +| `cot(pi + 10^(-30) * i)` | `1.785190…E-41 - 1E+30i` | `-1E+30i` | +| `sec(1/2 - 30 * i)` | 88 digits | 99 digits | + +Of 3798 values of `tanh`, `coth`, `sech`, `csch`, `tan`, `cot`, `sec`, `csc` and `1/z` at `a + b i`, for `a` in +`±10^(-k)` (`k` in 20, 40, 60, 80, 99, 120), `±1/3`, `±1`, `±10`, `±100` and `±1000` and `b` in `±1`, `±1/3`, +`±pi/4` and `±10^(-k)`, and at 26 ordinary and large arguments, master had 3040 right to a relative `1e-95` in each +part, 39 wrong, 289 with a small part dropped, 314 with a part right to fewer digits (96 of them to fewer than 85), +100 with a part within `1e-50` of an integer, which the downcasting makes that integer, and the other part right to +fewer than 95 digits, and 16 `NaN`. This branch has 3716 right, none wrong, 10 `NaN` (four poles, and `sech` and +`csch` past the exponents, as before) and 72 with a part made an integer and the other right to 80 digits, 16 of +which, `sech` near 0, had that part dropped. No part right on master is further than `2.1e-99` from +its value now. The last digit of the real part of `tan(3 ± 2 i)`, which was pinned, is now the correctly rounded +one, `…418949` where it was `…418947`; the true value is `…4189487`. Of the 8400 values of #2700's sweep, master had 12 wrong and 12 `NaN`, `tanh` of `-100 + b i` and of +`2 10^5 + b i`, and this branch has every one right. + ### A number past the working digits is not taken for an exact one **Not silent: wrong answers become exact ones.** At the default hundred digits, a product past about `10^50` diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs index 83215f129..458a316f5 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs @@ -43,13 +43,28 @@ internal static EDecimal CtxDivide(EDecimal a, EDecimal b) if (b.IsZero) return EDecimal.NaN; var context = MathS.Settings.DecimalPrecisionContext.Value; + // A quotient surely below 0.1 to as many more places as it has zeros after the point, and one more for + // the estimate, which is the size of each side from its exponent and its mantissa's bits, a third of a + // digit either way, then rounded to the digits: dividing to places, and to digits only where too few came + // of it, a quotient near 1e-13 kept 88 digits, and so did sec(1/2 - 30 i), the reciprocal of a cosine + // near 5e12. https://github.com/asc-community/AngouriMath/issues/2701 + if (!context.Precision.IsZero && Log10OfTheSizeOf(a) is { } ofA && Log10OfTheSizeOf(b) is { } ofB + && ofA - ofB < -1.5 && ofA - ofB > -1000) + return a.DivideToExponent(b, -context.Precision.Add(EInteger.FromInt32(1 + (int)System.Math.Ceiling(ofB - ofA)))) + .RoundToPrecision(context); var quotient = a.DivideToExponent(b, -context.Precision); - // 3.3 bits a digit, and five digits to spare; an unlimited context keeps the division to places. + // Fewer bits than a mantissa of all but one of the digits has, log2(10) = 3.32 a digit; an unlimited + // context keeps the division to places. if (!context.Precision.IsZero && quotient.IsFinite && !a.IsZero - && quotient.UnsignedMantissa.GetUnsignedBitLengthAsInt64() < (context.Precision.ToInt64Checked() - 5) * 3) + && quotient.UnsignedMantissa.GetUnsignedBitLengthAsInt64() < (long)((context.Precision.ToInt64Checked() - 1) * log2OfTen)) return a.Divide(b, context); return quotient; } + private const double log2OfTen = 3.3219280948873623; + private static double? Log10OfTheSizeOf(EDecimal value) + => value.IsFinite && !value.IsZero && value.Exponent.CanFitInInt32() + ? value.Exponent.ToInt32Unchecked() + value.UnsignedMantissa.GetUnsignedBitLengthAsInt64() * 0.30102999566398120 + : null; internal static EDecimal CtxMod(EDecimal a, EDecimal b) => a.Remainder(b, MathS.Settings.DecimalPrecisionContext); internal static EDecimal CtxPow(EDecimal a, EDecimal b) @@ -1290,42 +1305,48 @@ public static Complex Tan(Complex num) if (num is Real { EDecimal: var real } asReal) { var (sinOfReal, cosOfReal) = SinAndCosOfAReal(asReal, real, context); - return Real.CreateAtScale(cosOfReal.IsZero ? EDecimal.NaN : sinOfReal.Divide(cosOfReal, context), real); + // A cosine that is a residual of the argument is 0, as cos reads it: tan of pi/2 to the working digits, + // which tanh(pi/2 i) is, was 1.1E+101. https://github.com/asc-community/AngouriMath/issues/2701 + return Real.CreateAtScale(IsAResidualOfItsArgument(cosOfReal, PeriodicResidualScale(asReal, real, context), MathS.Settings.DowncastingEnabled) + ? EDecimal.NaN : sinOfReal.Divide(cosOfReal, context), real); } // Off the real line a part past the reach is the infinity it was, as for Exp. num = WithinTheSpecialFunctionsReach(num); - // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1 - - // tan z = sin z / cos z, but to avoid unnecessary repeated trig computations, use - // tan z = (sin(2x) + i sinh(2y)) / (cos(2x) + cosh(2y)) - // (see Abramowitz & Stegun 4.3.57 or derive by hand), and compute trig functions here. - - // This approach does not work for |y| > ~355, because sinh(2y) and cosh(2y) overflow, - // even though their ratio does not. In that case, divide through by cosh to get: - // tan z = (sin(2x) / cosh(2y) + i \tanh(2y)) / (1 + cos(2x) / cosh(2y)) - // which correctly computes the (tiny) real part and the (normal-sized) imaginary part. - - // The real part is sin(2 re) over the rest, a residual of 2 re as on the real line; the imaginary - // part cancels nothing. tan(1e-60 (1 + i)) is 1e-60 (1 + i), and was 0. - Real twiceRe = num.RealPart * Integer.Create(2); - var x2 = twiceRe.EDecimal; - var y2 = num.ImaginaryPart.EDecimal.Multiply(2, context); - var (sinh, cosh) = SinhAndCosh(y2, context); - var (sinOfX2, cosOfX2) = SinAndCosOfAReal(twiceRe, x2, context); - var x2Scale = PeriodicResidualScale(twiceRe, x2, context); - EDecimal ReScale(EDecimal divisor) => divisor.IsZero ? EDecimal.One : x2Scale.Divide(divisor.Abs(), context); - if (num.ImaginaryPart.EDecimal.Abs().LessThanOrEquals(4)) + // tan z = (sin x cos x + i sinh y cosh y) / (cos^2 x + sinh^2 y), and past |y| = 4, divided through by cosh^2 y, + // (sin x cos x sech^2 y + i tanh y) / (cos^2 x sech^2 y + tanh^2 y), which past the exponents is i sgn y. + // Nothing in it cancels but sin x or cos x, which is 0 where it is a residual of x, as for sin and cos, and + // tan(1e-60 (1 + i)) is 1e-60 (1 + i). Its denominator was cos 2x + cosh 2y, of which cos 2x is -1 at a pole, + // so near one it was the residual of that sum: tan(pi/2 + 10^(-60) i), which is 10^60 i, was -oo + oo i, + // and tanh(10^(-60) + pi/2 i) with it. https://github.com/asc-community/AngouriMath/issues/2701 + var (x, y) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); + // Within |y| <= 4 with ten digits more, rounded once, as the parts were to the last digit before: each + // of the products and the quotient rounds. Past it the exponentials take the context's exponents, past + // which cosh y is infinite, and the parts are as near 1 and 0 as the last digit tells. + var small = y.Abs().LessThanOrEquals(4); + var work = small ? Working(context, 10) : context.Value; + var (sinOfX, cosOfX) = SinAndCosOfAReal(num.RealPart, x, work); + var xScale = PeriodicResidualScale(num.RealPart, x, context); + var readsResiduals = MathS.Settings.DowncastingEnabled.Value; + if (IsAResidualOfItsArgument(sinOfX, xScale, readsResiduals)) + sinOfX = EDecimal.Zero; + if (IsAResidualOfItsArgument(cosOfX, xScale, readsResiduals)) + cosOfX = EDecimal.Zero; + var sinCos = sinOfX.Multiply(cosOfX, work); + var cosSquared = cosOfX.Multiply(cosOfX, work); + var (sinh, cosh) = SinhAndCosh(y, work); + if (small) { - var D = cosOfX2.Add(cosh, context); - return Complex.CreateAtScales(sinOfX2.Divide(D, context), sinh.Divide(D, context), ReScale(D), EDecimal.Zero); + var D = cosSquared.Add(sinh.Multiply(sinh, work), work); + return Complex.CreateAtScales(sinCos.Divide(D, work).RoundToPrecision(context), + sinh.Multiply(cosh, work).Divide(D, work).RoundToPrecision(context), EDecimal.Zero, EDecimal.Zero); } else { - var D = cosOfX2.Divide(cosh, context).Increment(); - return Complex.CreateAtScales( - sinOfX2.Divide(cosh, context).Divide(D, context), - y2.Tanh(context).Divide(D, context), - ReScale(cosh.Multiply(D, context)), EDecimal.Zero); + var tanh = y.Tanh(context); + var sech = cosh.IsFinite ? EDecimal.One.Divide(cosh, context) : EDecimal.Zero; + var sechSquared = sech.Multiply(sech, context); + var D = cosSquared.Multiply(sechSquared, context).Add(tanh.Multiply(tanh, context), context); + return Complex.CreateAtScales(sinCos.Multiply(sechSquared, context).Divide(D, context), tanh.Divide(D, context), EDecimal.Zero, EDecimal.Zero); } } @@ -1359,6 +1380,15 @@ public static Complex Cotan(Complex num) if (y.IsZero) return Real.CreateAtScale(sin, x).IsZero ? Integer.One / Tan(num) : Real.CreateAtScale(cos.Divide(sin, context), x.Abs().Divide(sin.Abs(), context)); + // Off the real line a sine or a cosine that is a residual of x is 0, as for sin and cos: the real part of + // cot(pi + 10^(-30) i), which is -10^30 i, was pi's residual over tanh^2(10^(-30)), 1.8E-41, above the + // tolerance of a number near 0 and below that of its scale. https://github.com/asc-community/AngouriMath/issues/2701 + var xScale = PeriodicResidualScale(num.RealPart, x, context); + var readsResiduals = MathS.Settings.DowncastingEnabled.Value; + if (IsAResidualOfItsArgument(sin, xScale, readsResiduals)) + sin = EDecimal.Zero; + if (IsAResidualOfItsArgument(cos, xScale, readsResiduals)) + cos = EDecimal.Zero; var (sinh, cosh) = SinhAndCosh(y, context); // Past the context's exponents cosh y is infinite, tanh y its sign and sech y 0: cot(1 - 3000 i) is i. var (tanh, sech) = cosh.IsFinite @@ -1371,7 +1401,7 @@ public static Complex Cotan(Complex num) var re = sin.Multiply(cos, context).Multiply(sechSquared, context).Divide(denominator, context); var im = tanh.Negate().Divide(denominator, context); // sin x cos x is a residual of x through whichever of the two is small. - var reScale = PeriodicResidualScale(num.RealPart, x, context).Multiply(sin.Abs().Add(cos.Abs(), context), context).Multiply(sechSquared, context).Divide(denominator, context); + var reScale = xScale.Multiply(sin.Abs().Add(cos.Abs(), context), context).Multiply(sechSquared, context).Divide(denominator, context); return Complex.CreateAtScales(re, im, reScale, EDecimal.Zero); } @@ -1485,9 +1515,18 @@ internal static Complex ExpDifference(Complex v, Complex d) } // Each sum rounded: taken exactly, 1 added to e^(10^7) was an integer of four million digits, and // tanh(10^7) did not return. https://github.com/asc-community/AngouriMath/issues/2563 - EDecimal Size(Complex z) => z.RealPart.EDecimal.Abs().Add(z.ImaginaryPart.EDecimal.Abs(), work); - var scale = Size(lower).Multiply(Size(power).Add(EDecimal.One, work), work).ScaleByPowerOfTen(-extra); - return Complex.CreateAtScales(product.RealPart.EDecimal.RoundToPrecision(context), product.ImaginaryPart.EDecimal.RoundToPrecision(context), scale, scale); + // Each part against what it is a sum of: only Re(e^d) - 1 cancels, at the size of |Re(e^d)| + 1, and each + // part of the product takes it through one part of e^v and Im(e^d) through the other. Against one scale + // for both, Im(e^(-200 + 2 i) - 1), 1.3E-87, was read against the 1 and dropped, and tanh(-100 + i), whose + // quotient takes it once from each side, had half its imaginary part. + // https://github.com/asc-community/AngouriMath/issues/2701 + var (lowerRe, lowerIm) = (lower.RealPart.EDecimal.Abs(), lower.ImaginaryPart.EDecimal.Abs()); + var cancelled = power.RealPart.EDecimal.Abs().Add(EDecimal.One, work); + var powerIm = power.ImaginaryPart.EDecimal.Abs(); + EDecimal Scale(EDecimal withTheOne, EDecimal withTheSine) + => withTheOne.Multiply(cancelled, work).Add(withTheSine.Multiply(powerIm, work), work).ScaleByPowerOfTen(-extra); + return Complex.CreateAtScales(product.RealPart.EDecimal.RoundToPrecision(context), product.ImaginaryPart.EDecimal.RoundToPrecision(context), + Scale(lowerRe, lowerIm), Scale(lowerIm, lowerRe)); } /// 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 273be0a45..2aa23ffbb 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 @@ -135,6 +135,8 @@ public partial record Sumf /// protected override Entity InnerSimplify(bool isExact) { + if (!isExact && Functions.HyperbolicSpellings.Cosh(Augend, Addend) is { } cosh) + return cosh; SimplifyALongLeftSpineFirst(this, isExact); return ExpandOnTwoArguments(Augend, Addend, (augend, addend) => (augend, addend) switch @@ -198,6 +200,8 @@ partial record Minusf /// private static Entity? DifferenceOfExponentials(Entity minuend, Entity subtrahend) { + if (Functions.HyperbolicSpellings.Sinh(minuend, subtrahend) is { } sinh) + return sinh; if (ExponentOfE(minuend) is not { } u || ExponentOfE(subtrahend) is not { } v) return null; if ((u - v).Evaled is not Complex d || v.Evaled is not Complex exponent || !d.IsFinite || !exponent.IsFinite) @@ -253,6 +257,7 @@ public partial record Divf /// protected override Entity InnerSimplify(bool isExact) => + !isExact && Functions.HyperbolicSpellings.TanhOrCoth(Dividend, Divisor) is { } quotient ? quotient : ExpandOnTwoArguments(Dividend, Divisor, (a, b) => (a, b) switch { diff --git a/Sources/AngouriMath/Functions/ExponentialQuotients.cs b/Sources/AngouriMath/Functions/ExponentialQuotients.cs index 7538c9e31..ca1f25211 100644 --- a/Sources/AngouriMath/Functions/ExponentialQuotients.cs +++ b/Sources/AngouriMath/Functions/ExponentialQuotients.cs @@ -5,7 +5,9 @@ // Website: https://am.angouri.org. // +using PeterO.Numbers; using static AngouriMath.Entity; +using static AngouriMath.Entity.Number; namespace AngouriMath.Functions { @@ -54,4 +56,71 @@ internal static Entity Rewritten(Entity expression) private static bool IsConstant(Entity expression) => !expression.Vars.Any(); } + + /// + /// cosh, sinh, tanh and coth of a number off the real line, evaluated where they are + /// spelled as the parser writes them, e^w + e^(-w), e^w - e^(-w), (e^w - 1)/(e^w + 1) and + /// (e^w + 1)/(e^w - 1), through the trigonometric function of i w. + /// + /// + /// Each spelling, evaluated as written, combines two powers rounded to the working digits, and a part that is + /// small beside them cancels there: tanh(10^(-60) + i) has the real part 3.4E-60, which the + /// quotient of e^(2 z) - 1 by e^(2 z) + 1 leaves below the residual tolerance of its terms, so it + /// was 1.557...i; sech(10^(-60) + i) lost its imaginary part the same way in e^z + e^(-z). + /// cos(i w), sin(i w), tan(i w) and cot(i w) take each part as a product or a quotient + /// of the sine or the cosine of one part and a hyperbolic function of the other, which cancels nothing but the + /// residual of a multiple of pi/2, and read that residual as the real line does. A real w is left + /// to the spelling, whose real exponentials cancel nothing. https://github.com/asc-community/AngouriMath/issues/2701 + /// + internal static class HyperbolicSpellings + { + /// e^w + e^(-w), 2 cos(i w), or . + internal static Entity? Cosh(Entity augend, Entity addend) + => Opposite(augend, addend) is { } w ? two * Cos(Complex.ImaginaryOne * w) : null; + + /// e^w - e^(-w), -2 i sin(i w), or . + internal static Entity? Sinh(Entity minuend, Entity subtrahend) + => Opposite(minuend, subtrahend) is { } w ? minusTwoI * Sin(Complex.ImaginaryOne * w) : null; + + /// + /// (e^w - 1)/(e^w + 1), tanh(w/2) = -i tan(i w/2), and (e^w + 1)/(e^w - 1), + /// coth(w/2) = i cot(i w/2), or . + /// + internal static Entity? TanhOrCoth(Entity dividend, Entity divisor) + { + if (PowerBesideOne(dividend) is not var (power, above) || PowerBesideOne(divisor) is not var (same, below) + || above == below || power != same || OffTheRealLine(power) is not { } w) + return null; + var half = Complex.ImaginaryOne * w * oneHalf; + return above ? Complex.ImaginaryOne * Cotan(half) : Complex.MinusImaginaryOne * Tan(half); + } + + [ConstantField] private static readonly Complex two = Integer.Create(2); + [ConstantField] private static readonly Complex minusTwoI = Complex.Create(EDecimal.Zero, EDecimal.FromInt32(-2)); + [ConstantField] private static readonly Complex oneHalf = Rational.Create(EInteger.One, EInteger.FromInt32(2)); + + /// The exponent w of e^w and e^(-w), evaluated, where it is a finite number off the real line. + private static Complex? Opposite(Entity one, Entity other) + { + if (OffTheRealLine(one) is not { } w || ExponentOfE(other)?.Evaled is not Complex v || !PartsAreFinite(v)) + return null; + return w.RealPart.EDecimal.CompareTo(v.RealPart.EDecimal.Negate()) == 0 + && w.ImaginaryPart.EDecimal.CompareTo(v.ImaginaryPart.EDecimal.Negate()) == 0 ? w : null; + } + + /// The power e^w of e^w + 1, 1 + e^w or e^w - 1, and whether the 1 is added. + private static (Entity Power, bool Added)? PowerBesideOne(Entity sum) => sum switch + { + Sumf(var power, Integer(1)) when ExponentOfE(power) is { } => (power, true), + Sumf(Integer(1), var power) when ExponentOfE(power) is { } => (power, true), + Minusf(var power, Integer(1)) when ExponentOfE(power) is { } => (power, false), + _ => null, + }; + + private static Complex? OffTheRealLine(Entity power) + => ExponentOfE(power)?.Evaled is Complex w and not Real && PartsAreFinite(w) ? w : null; + + private static Entity? ExponentOfE(Entity power) + => power is Powf(var @base, var exponent) && @base == MathS.e ? exponent : null; + } } diff --git a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs index 86dbe0c27..4d64c3c95 100644 --- a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs @@ -994,6 +994,45 @@ public void Issue2700_APartThatIsZeroForTheExactArgumentIsZeroAtAnySize(string e public void Issue2700_ASmallPartThatIsNotZeroKeepsItsDigits(string expression, string real, string imaginary) => AssertTheParts(expression, real, imaginary); + // tanh and coth are spelled through e^(2 z) and sech through e^z + e^(-z), and a part that is small beside the + // powers cancelled in the quotient or the sum, or, where e^(2 z) - 1 read its imaginary part against the 1, + // came out half its value. Off the real line each is now the trigonometric function of i z, whose parts cancel + // nothing but a residual of a multiple of pi/2. tan's denominator was cos 2x + cosh 2y, a residual itself near a + // pole, and a reciprocal near 1e-13 kept 88 digits. https://github.com/asc-community/AngouriMath/issues/2701 + [Theory] + [InlineData("tanh(10^(-60) + i)", "3.4255188208147597609416789335411366480537474320573847658685147677426613633119282718199654663729661040491632041e-60", "1.5574077246549022305069748074583601730872507723815200383839466056988613971517272895550999652022429838046338214")] + [InlineData("coth(10^(-60) + i)", "1.4122829274373919146093350045416249023722951143508172080532726064992790297511263545548719147046847799652396384e-60", "-6.4209261593433070300641998659426562023027811391817137910116228042627685683916467219848291976019680465814306596e-1")] + [InlineData("tanh(-100 + i)", "-1", "2.5167471015094272934101898783102828074005582122737891081340521388465021958808017611804118782676987107949901723e-87")] + [InlineData("tanh(-100 + 1/3 * i)", "-1", "1.711519645414178845000024875177812563876077339303822992144551928561143464670078024674771486738622659561287214e-87")] + [InlineData("tanh(100 + i)", "1", "2.5167471015094272934101898783102828074005582122737891081340521388465021958808017611804118782676987107949901723e-87")] + [InlineData("sech(10^(-60) + i)", "1.8508157176809256179117532413986501934703966550940092988351582778588154112615967059218414132873066711491035116", "-2.8824746956289802665718428062830234809175946152002545363838862476071379629293072973728966820109409050902035827e-60")] + [InlineData("tanh(10^(-40) + pi/4 * i)", "1.9999999999999999999999999999999999999999999999999999999999999999999999999999999733333333333333333333333333333e-40", "1")] + [InlineData("tanh(10^(-60) * i)", "0", "1e-60")] + [InlineData("sec(1/2 - 30 * i)", "1.6424173476397911617255056134725226441377873896137147980330076026943253376619069102067098631068990088955812177e-13", "-8.9725668637825236383503514063406090903103348704892352607890233457315194036245297953981899215878129732616743722e-14")] + [InlineData("csc(1/2 - 30 * i)", "8.9725668637825236383503517332800695943452183126782723561947482413216551399510162169168703314349265752368943476e-14", "1.6424173476397911617255056157910087379414697353292625399730459624676757773590344031846372999728687390109501598e-13")] + [InlineData("tan(pi/2 + 10^(-60) * i)", "0", "1e+60")] + [InlineData("cot(pi + 10^(-30) * i)", "0", "-1.0000000000000000000000000000000000000000000000000000000000003333333333333333333333333333333333333333333333333e+30")] + public void Issue2701_ASmallPartOfAHyperbolicFunctionOrAReciprocalKeepsItsDigits(string expression, string real, string imaginary) + => AssertTheParts(expression, real, imaginary); + + // A real quotient near 1e-13 keeps every digit too, as the reciprocal of sqrt(3) 10^12 does. + // https://github.com/asc-community/AngouriMath/issues/2701 + [Fact] + public void Issue2701_ASmallQuotientKeepsEveryDigit() + { + var quotient = Assert.IsAssignableFrom("1 / (sqrt(3) * 10^12)".ToEntity().Evaled).EDecimal; + var expected = EDecimal.FromString("5.7735026918962576450914878050195745564760175127012687601860232648397767230293334569371539558574952522520871381e-13"); + Assert.True(quotient.Subtract(expected).Abs().CompareTo(expected.Multiply(EDecimal.FromString("1E-98"))) <= 0, quotient.ToString()); + } + + // tanh(pi/2 i) is i tan(pi/2), a pole, and the tangent of pi/2 to the working digits is one: its cosine is a residual. + // https://github.com/asc-community/AngouriMath/issues/2701 + [Theory] + [InlineData("tanh(pi/2 * i)")] + [InlineData("coth(pi * i)")] + public void Issue2701_APoleOfTanhOffTheRealLineHasNoValue(string expression) + => Assert.Equal(MathS.NaN, expression.ToEntity().Evaled); + private static void AssertTheParts(string expression, string real, string imaginary) { var number = Assert.IsAssignableFrom(expression.ToEntity().Evaled); diff --git a/Sources/Tests/UnitTests/Core/NumericDigits.cs b/Sources/Tests/UnitTests/Core/NumericDigits.cs index 2c9fa9d40..be10fc9be 100644 --- a/Sources/Tests/UnitTests/Core/NumericDigits.cs +++ b/Sources/Tests/UnitTests/Core/NumericDigits.cs @@ -41,8 +41,8 @@ public sealed class NumericDigits [Fact] public void Cos3M2I() => Test(Cos(3-2*i), "-3.724545504915322565473970703255972528674965773215330726785894568664950105906529288911014829414174408 + 0.5118225699873846088344638498018756342455566094907438674553837912358533904574111940998404122618726210i"); [Fact] public void Tan1() => Test(Tan(1), "1.557407724654902230506974807458360173087250772381520038383946605698861397151727289555099965202242984"); [Fact] public void TanI() => Test(Tan(i), "0.7615941559557648881194582826047935904127685972579365515968105001219532445766384834589475216736767144i"); - [Fact] public void Tan3P2I() => Test(Tan(3+2*i), "-0.009884375038322493720314034303501210979618133534670390318610106061155603556792543443355828521930418947 + 0.9653858790221331242784802693945606858797296500057577736369082400666397728539675500957543613480053582i"); - [Fact] public void Tan3M2I() => Test(Tan(3-2*i), "-0.009884375038322493720314034303501210979618133534670390318610106061155603556792543443355828521930418947 - 0.9653858790221331242784802693945606858797296500057577736369082400666397728539675500957543613480053582i"); + [Fact] public void Tan3P2I() => Test(Tan(3+2*i), "-0.009884375038322493720314034303501210979618133534670390318610106061155603556792543443355828521930418949 + 0.9653858790221331242784802693945606858797296500057577736369082400666397728539675500957543613480053582i"); + [Fact] public void Tan3M2I() => Test(Tan(3-2*i), "-0.009884375038322493720314034303501210979618133534670390318610106061155603556792543443355828521930418949 - 0.9653858790221331242784802693945606858797296500057577736369082400666397728539675500957543613480053582i"); [Fact] public void Cotan1() => Test(Cotan(1), "0.6420926159343307030064199865942656202302781139181713791011622804262768568391646721984829197601968046"); [Fact] public void CotanPi() => Test(Cotan(pi), "NaN"); [Fact] public void CotanHalfPi() => Test(Cotan(0.5m * pi), "0");