From b19634f947ec32a9a4efe6e0f35d29ee760ebf3f Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Tue, 1 Dec 2026 17:58:00 +0000 Subject: [PATCH] Keep every part of a complex value past 10^50 (#2675) The complex paths of the exponential, the trigonometric functions and the exponential and trigonometric integrals measured a sine's or a cosine's residual against the size of its argument, which past 10^50 took every one of them for a residual. They measure it against |t| up to 1, sqrt|t| past it for a decimal, and 1 for an exact rational, which is now reduced exactly on the complex paths and in Ei, Si and Ci too. arcsin and arccos of a non-real argument are written as Hull, Fairgrieve and Tang write them: the real part from alpha - |x| and v from alpha - 1, each a sum of like signs, so that nothing cancels at any size and neither part is a residual. An infinite argument goes off along its direction. A root of an exact non-real number is not searched for among the reals. Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 50 ++++++ .../Entity.Continuous.Complex.Definition.cs | 6 +- .../Continuous/Number/ExponentialIntegrals.cs | 22 ++- .../Entity/Continuous/Number/Operators.cs | 156 +++++++++++++----- .../Number/TrigonometricIntegrals.cs | 21 ++- .../Common/NumericsRegressionTest.cs | 58 +++++++ 6 files changed, 254 insertions(+), 59 deletions(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 154a2ae50..16c2f63fb 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -103,6 +103,56 @@ mpmath's at 4500 digits. | `Ci(exp(300))` | `0` | `NaN` | below `1e-130`, sign unknown | | `cos(10^150/3)` | `-0.44819…` | `0.80881903093981837173…` | `0.80881903093981837173…` | +### A complex value past 10^50 keeps every part of it + +**Silent: wrong numbers become right ones.** The complex paths of the exponential, the trigonometric functions and the +exponential and trigonometric integrals took a part for a rounding residual when it was below half the working digits of +the argument's size. A sine or a cosine is at most 1, so past `10^50` every one was a residual: `e^(10^60 i)` kept its real +part alone, `tanh(10^60 i)` came back with a real part of -2.2 where it has none, and `Ci(10^50)` was 0. A part is now a +residual against `|t|` for an argument `t` up to 1, against `sqrt|t|` past it for a decimal, half the digits its reduction +by `2 pi` leaves, and against 1 for an exact rational, which is reduced exactly; so `Ci` and `Si` of an exact `10^500`, +which were `NaN`, have values. `arcsin` and `arccos` of a non-real argument took their real part from +`(|z + 1| - |z - 1|)/2`, two moduli of the argument's size, so that past `10^110` it had no digits and `arcsin(10^200)` +was 0, and dropped their imaginary part against the size of the argument. They are now written as Hull, Fairgrieve and +Tang write them, with nothing cancelling, at any size up to the exponents' end; past `10^1000` they were `+-oo i` with a +real part that was `pi/2` whatever the direction, and an infinite argument now goes off along its direction. And a root +of an exact non-real number was taken for a real one when its imaginary part was below the tolerance: +`sqrt(10^50 + i)` was `10^25`. `Complex.CreatePolar` measures its residuals the same way. Measured on master +(4674e6656) and on this branch; the true values are mpmath's at 700 to 2000 digits, `arcsin` of a real past 1 taken +from below the axis as the library takes it ([#2675](https://github.com/asc-community/AngouriMath/issues/2675)). + +| `.Evaled` | Was (master) | Now | +|---|---|---| +| `arcsin(10^100)` | `1.5707963267…` | `1.5707963267… - 230.95165647…i` | +| `arcsin(10^200)` | `0` | `1.5707963267… - 461.21016577…i` | +| `arcsin(10^100 * i)` | `0` | `230.95165647…i` | +| `arccos(10^500)` | `1.5707963267…` | `1151.98569367…i` | +| `arccos(10^100 * i)` | `1.5707963267…` | `1.5707963267… - 230.95165647…i` | +| `arcsin(10^1500)` | `1.5707963267… - oo i` | `1.5707963267… - 3454.57078667…i` | +| `arcsin(10^1500 * i)` | `1.5707963267… + oo i` | `3454.57078667…i` | +| `arccos(-10^1500)` | `+oo i` | `3.1415926535… + 3454.57078667…i` | +| `arcsin(-oo)` | `1.5707963267… - oo i` | `-1.5707963267… - oo i` | +| `arcsin(+oo * i)` | `1.5707963267… + oo i` | `+oo i` | +| `e^(10^60 * i)` | `-0.5571829482…` | `-0.5571829482… + 0.8303897652…i` | +| `sin(10^60 + i)` | `1.2813583660…` | `1.2813583660… - 0.6548020658…i` | +| `tanh(10^60 * i)` | `-2.2211011728… - 1.4903359261…i` | `-1.4903359261…i` | +| `tanh(10^50 * i)` | `-1.65663… + 1.2870997095…i` | `1.2870997095…i` | +| `coth(10^50 * i)` | `-0.376417… - 0.292454…i` | `-0.7769405840…i` | +| `Ci(10^50)` | `0` | `-7.8967249342…E-51` | +| `Ci(10^100)` | `0` | `-3.7237612366…E-101` | +| `Ci(10^500)` | `NaN` | `3.1102693090…E-501` | +| `Si(10^500)` | `NaN` | `1.5707963267…` | +| `Ei(10^50 * i)` | `3.1415926535…i` | `-7.8967249342…E-51 + 3.1415926535…i` | +| `Ei(-10^60 * i)` | `-3.1415926535…i` | `8.3038976521…E-61 - 3.1415926535…i` | +| `sqrt(10^50 + i)` | `10^25` | `10^25 + 5E-26i` | + +A decimal past `10^(precision - 16)` still has no sine to give, and `10^100 * i` is such a decimal, its imaginary part +being past the digits that make it an integer: `tanh(10^100 * i)` and `Ei(10^100 * i)` stay `NaN`. + +The new `arcsin` and `arccos` also move the last digits of moderate arguments where one part is far larger than the +other: of 914 sampled evaluations of the functions above, 22 changed, all of them `arcsin`, `arccos` or `arcsec`, and each +is nearer mpmath's than it was. `arcsin(10^40 - 3/7 i)` had a real part wrong from its 39th digit, and now from its 100th. + ### 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/Entity.Continuous.Complex.Definition.cs b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Complex.Definition.cs index 10b14f0bc..df8b9e3b6 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Complex.Definition.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Complex.Definition.cs @@ -180,8 +180,10 @@ public void Deconstruct(out Real realPart, out Real imaginaryPart) => public static Complex CreatePolar(EDecimal magnitude, EDecimal phase) { var context = MathS.Settings.DecimalPrecisionContext; - // The residual of a cosine or a sine is the magnitude's: cos(pi/2) leaves 1e-100 of it. - var scale = magnitude.Abs(); + // The residual of a cosine or a sine is its argument's times the magnitude: cos(pi/2) leaves 1e-100 + // of it, and the root of 1 + 10^(-50) i, 1 + 5 10^(-51) i, lost its imaginary part at the magnitude + // alone, so that sqrt(10^50 + i) was real. https://github.com/asc-community/AngouriMath/issues/2675 + var scale = magnitude.Abs().Multiply(PeriodicResidualScale(phase, exact: false, context), context); return CreateAtScales(magnitude.Multiply(phase.Cos(context), context), magnitude.Multiply(phase.Sin(context), context), scale, scale); } diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs index 5d9d42056..a5cff754b 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/ExponentialIntegrals.cs @@ -68,7 +68,10 @@ public static Complex Ei(Complex z) if (digitsOfTheRest < -(context.Precision.ToInt32Checked() + 2)) return Complex.Create(EDecimal.Zero, im.IsNegative ? EDecimal.PI(context).Negate() : EDecimal.PI(context)); } - var ei = Ei(re, im, context, extraDigits: 0); + // An exact imaginary part is reduced exactly: Ei(10^100 i) was NaN for want of the digits of cos(10^100). + // https://github.com/asc-community/AngouriMath/issues/2675 + var (exactIm, imIsExact) = PeriodicArgument(z.ImaginaryPart, im, context); + var ei = Ei(re, exactIm, context, extraDigits: 0, imIsExact); // A part is a residual only against what was added to make it, not against 1: Ei(-130) is about // -2.7 * 10^(-59). https://github.com/asc-community/AngouriMath/issues/1944 return Complex.CreateAtScales(ei.Re.RoundToPrecision(context), ei.Im.RoundToPrecision(context), ei.ReScale, ei.ImScale); @@ -109,12 +112,13 @@ public static Complex Li(Complex z) /// more, before any rounding back, and for each part the scale it is a /// residual against at 's precision. /// - private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) Ei(EDecimal re, EDecimal im, EContext context, int extraDigits) + /// says that is exactly the number asked about. + private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) Ei(EDecimal re, EDecimal im, EContext context, int extraDigits, bool exactIm = false) { var precision = context.Precision.ToInt32Checked() + extraDigits; var modulus = Math.Sqrt(Math.Pow(re.ToDouble(), 2) + Math.Pow(im.ToDouble(), 2)); if (modulus > (precision + 5) * Math.Log(10)) - return EiByTheAsymptoticSeries(re, im, Working(context, extraDigits + 10)); + return EiByTheAsymptoticSeries(re, im, Working(context, extraDigits + 10), exactIm); // The digits the terms cancel off the positive axis, and ten over. var cancelled = (int)Math.Ceiling((modulus - re.ToDouble()) / Math.Log(10)); var work = Working(context, extraDigits + cancelled + 10); @@ -162,7 +166,7 @@ private static ((EDecimal Re, EDecimal Im) Value, (EDecimal Re, EDecimal Im) Sca /// e^z/z sum_k k!/z^k + i pi sgn(Im z), cut at its smallest term, and for each part the sizes of the /// products added to make it. /// - private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) EiByTheAsymptoticSeries(EDecimal re, EDecimal im, EContext work) + private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) EiByTheAsymptoticSeries(EDecimal re, EDecimal im, EContext work, bool exactIm) { var epsilon = EDecimal.Create(EInteger.One, EInteger.FromInt32(-work.Precision.ToInt32Checked())); // 1/z = (re - i im)/|z|^2 @@ -184,14 +188,16 @@ private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) Ei } // e^z/z = e^re (cos im + i sin im) (re - i im)/|z|^2 var growth = re.Exponential(work); - var (cos, sin) = (im.Cos(work), im.Sin(work)); + var (sin, cos) = exactIm ? InternalAMExtensions.SinAndCosOfAnExactArgument(im, work) : InternalAMExtensions.SinAndCos(im, work); var exponential = (growth.Multiply(cos, work), growth.Multiply(sin, work)); var factor = Multiply(exponential, reciprocal, work); var (valueRe, valueIm) = Multiply(factor, sum, work); - // Each part of e^z/z is a sum of two products, and cos im and sin im are known to |im| times the - // working digits, as on the real line; the value's parts add those parts times the sum's. + // Each part of e^z/z is a sum of two products, and cos im and sin im are residuals against + // PeriodicResidualScale, as on the real line; the value's parts add those parts times the sum's. + // Against |im| itself, Ci(10^50), about -7.9e-51, was 0. + // https://github.com/asc-community/AngouriMath/issues/2675 var (absRe, absIm) = (re.Abs(), im.Abs()); - var trigonometric = absIm.Multiply(absRe.Add(absIm, work), work); + var trigonometric = PeriodicResidualScale(im, exactIm, work).Multiply(absRe.Add(absIm, work), work); var factorReScale = growth.Multiply(cos.Abs().Multiply(absRe, work).Add(sin.Abs().Multiply(absIm, work), work).Add(trigonometric, work), work).Divide(squaredModulus, work); var factorImScale = growth.Multiply(sin.Abs().Multiply(absRe, work).Add(cos.Abs().Multiply(absIm, work), work).Add(trigonometric, work), work).Divide(squaredModulus, work); var reScale = factorReScale.Multiply(sum.Re.Abs(), work).Add(factorImScale.Multiply(sum.Im.Abs(), work), work); diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs index 706984ace..4f870fc42 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs @@ -417,6 +417,11 @@ private static bool CanHaveARealRoot(Complex @base, EInteger rootPower) => internal static Real? FindGoodRoot(Complex @base, Integer power) { + // A base whose imaginary part is an exact rational other than 0 is no real number, and no real root has + // it for a power; the search below takes a root for real once its imaginary part is under the + // downcasting's tolerance, and sqrt(10^50 + i) was 10^25. https://github.com/asc-community/AngouriMath/issues/2675 + if (@base.ImaginaryPart is Rational { ERational.IsZero: false }) + return null; // Searched at the size of one, by an exact power of ten: the candidates are rounded with // the zero range at 1e-6, so a root below it was the integer 0, and 0 ^ q was within 1e-6 // of the base, so sqrt(1/10^20) was 0. Scaled, it is sqrt(1) / 10^10. @@ -568,12 +573,13 @@ public static Complex Exp(Complex x) if (imaginary.IsZero) return Real.CreateAtScale(expReal, EDecimal.Zero); // From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,7dc9c2ee4f99814a - var cosImaginary = expReal.Multiply(imaginary.Cos(context), context); - var sinImaginary = expReal.Multiply(imaginary.Sin(context), context); + var (sinOfImaginary, cosOfImaginary) = SinAndCosOfAReal(x.ImaginaryPart, imaginary, context); + var cosImaginary = expReal.Multiply(cosOfImaginary, context); + var sinImaginary = expReal.Multiply(sinOfImaginary, context); // The residual of a cosine or a sine is its argument's, as on the real line, times the modulus: // e^(i pi) leaves 1e-100 i of pi, and e^(1e-60 i) is 1 + 1e-60 i, whose sine was 0 at the // modulus alone. - var scale = expReal.Multiply(imaginary.Abs(), context); + var scale = expReal.Multiply(PeriodicResidualScale(x.ImaginaryPart, imaginary, context), context); return Complex.CreateAtScales(cosImaginary, sinImaginary, scale, scale); } @@ -798,7 +804,7 @@ private static Complex ByThePolarForm(EDecimal baseReal, EDecimal baseImaginary, // The residual of a cosine or a sine is its argument's, as on the real line, and the argument is a // sum that may itself cancel, so it is that of the larger term; times the modulus. At the modulus // alone, e^(1e-60 i) was 1. - var scale = t.Abs().Multiply(fromTheBase.Abs().Add(fromTheModulus.Abs(), context), context); + var scale = t.Abs().Multiply(PeriodicResidualScale(fromTheBase.Abs().Add(fromTheModulus.Abs(), context), exact: false, context), context); return Complex.CreateAtScales(t.Multiply(newRho.Cos(context), context), t.Multiply(newRho.Sin(context), context), scale, scale); } @@ -988,6 +994,27 @@ private static (EDecimal Sin, EDecimal Cos) SinAndCosOfAReal(Real real, EDecimal var (value, exact) = PeriodicArgument(real, written, context); return exact ? InternalAMExtensions.SinAndCosOfAnExactArgument(value, context) : InternalAMExtensions.SinAndCos(value, context); } + + /// + /// The size a residual of the sine or the cosine of is measured against: |t| up to + /// 1, as on the real line, where cos(pi/2) leaves a residual of pi's digits; past it, sqrt|t| for a + /// decimal, whose reduction by 2 pi keeps the working digits less those t has before its point, + /// so that a residual is below half of what is left; and 1 for an exact rational, which is reduced exactly. + /// Measured against |t|, a sine or a cosine, which is at most 1, was a residual wherever t was past + /// 10^50: e^(10^60 i) kept its real part alone, and tanh(10^60 i) had a real part of -2.2. + /// https://github.com/asc-community/AngouriMath/issues/2675 + /// + internal static EDecimal PeriodicResidualScale(EDecimal t, bool exact, EContext context) + { + var size = t.Abs(); + if (!size.IsFinite || size.CompareTo(EDecimal.One) <= 0) + return size; + return exact ? EDecimal.One : size.SqrtByIntegerRoot(context); + } + + /// + private static EDecimal PeriodicResidualScale(Real real, EDecimal written, EContext context) + => PeriodicResidualScale(written, real is Rational, context); [ConstantField] private static readonly EDecimal tenToTheEight = EDecimal.FromString("1E+8"); /// @@ -1022,10 +1049,11 @@ public static Complex Sin(Complex num) var (sinh, cosh) = SinhAndCosh(im, context); // Only sin(re) and cos(re) cancel, each a residual of re as it is on the real line, and each part // is one of them times sinh(im) or cosh(im): sin(pi + 1e-60 i) is -1e-60 i, and was 0. - var reScale = re.Abs(); + var (sinOfRe, cosOfRe) = SinAndCosOfAReal(num.RealPart, re, context); + var reScale = PeriodicResidualScale(num.RealPart, re, context); return Complex.CreateAtScales( - re.Sin(context).Multiply(cosh, context), - re.Cos(context).Multiply(sinh, context), + sinOfRe.Multiply(cosh, context), + cosOfRe.Multiply(sinh, context), reScale.Multiply(cosh, context), reScale.Multiply(sinh.Abs(), context)); } @@ -1085,10 +1113,11 @@ public static Complex Cos(Complex num) var (re, im) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); var (sinh, cosh) = SinhAndCosh(im, context); // As for Sin: cos(pi/2 + 1e-60 i) is -1e-60 i, and was 0. - var reScale = re.Abs(); + var (sinOfRe, cosOfRe) = SinAndCosOfAReal(num.RealPart, re, context); + var reScale = PeriodicResidualScale(num.RealPart, re, context); return Complex.CreateAtScales( - re.Cos(context).Multiply(cosh, context), - -re.Sin(context).Multiply(sinh, context), + cosOfRe.Multiply(cosh, context), + -sinOfRe.Multiply(sinh, context), reScale.Multiply(cosh, context), reScale.Multiply(sinh.Abs(), context)); } @@ -1116,20 +1145,23 @@ public static Complex Tan(Complex num) // 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. - var x2 = num.RealPart.EDecimal.Multiply(2, context); + 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); - EDecimal ReScale(EDecimal divisor) => divisor.IsZero ? EDecimal.One : x2.Abs().Divide(divisor.Abs(), 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)) { - var D = x2.Cos(context).Add(cosh, context); - return Complex.CreateAtScales(x2.Sin(context).Divide(D, context), sinh.Divide(D, context), ReScale(D), EDecimal.Zero); + var D = cosOfX2.Add(cosh, context); + return Complex.CreateAtScales(sinOfX2.Divide(D, context), sinh.Divide(D, context), ReScale(D), EDecimal.Zero); } else { - var D = x2.Cos(context).Divide(cosh, context).Increment(); + var D = cosOfX2.Divide(cosh, context).Increment(); return Complex.CreateAtScales( - x2.Sin(context).Divide(cosh, context).Divide(D, context), + sinOfX2.Divide(cosh, context).Divide(D, context), y2.Tanh(context).Divide(D, context), ReScale(cosh.Multiply(D, context)), EDecimal.Zero); } @@ -1160,7 +1192,7 @@ public static Complex Cotan(Complex num) if (!x.IsFinite || !y.IsFinite) return Integer.One / Tan(num); } - var (sin, cos) = ofAReal ?? InternalAMExtensions.SinAndCos(x, context); + var (sin, cos) = ofAReal ?? SinAndCosOfAReal(num.RealPart, x, context); // sin x is a residual of x as on the real line, and 0 at a pole: cot of pi to the working digits is NaN. if (y.IsZero) return Real.CreateAtScale(sin, x).IsZero ? Integer.One / Tan(num) @@ -1177,7 +1209,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 = x.Abs().Multiply(sin.Abs().Add(cos.Abs(), context), context).Multiply(sechSquared, context).Divide(denominator, context); + var reScale = PeriodicResidualScale(num.RealPart, x, context).Multiply(sin.Abs().Add(cos.Abs(), context), context).Multiply(sechSquared, context).Divide(denominator, context); return Complex.CreateAtScales(re, im, reScale, EDecimal.Zero); } @@ -1202,25 +1234,54 @@ public static Complex Cotan(Complex num) // arccos(w) = arccos(beta) - i sign(y) log(alpha + sqrt(alpha^2 - 1)) // So alpha and beta together give us arcsin(w) and arccos(w). - static (EDecimal beta, EDecimal v, EDecimal alpha) ArcSinCosInner(Complex num, EContext context) + // Neither part is taken from beta itself, which is a difference of two moduli of the argument's size, nor + // v from alpha^2 - 1: past 10^(working digits) every digit of rho - sigma cancelled and arcsin(10^200) was 0, + // and arcsin(beta) near beta = 1 keeps half the digits beta has. With alpha - |x| and alpha - 1 written as + // sums of like signs, as Hull, Fairgrieve and Tang do, + // arcsin(beta) = arctan(|x| / sqrt(alpha^2 - x^2)) sgn x, arccos(beta) = arctan2(sqrt(alpha^2 - x^2), x), + // v = sgn(y) ln(1 + (alpha - 1) + sqrt((alpha - 1)(alpha + 1))), + // and nothing cancels but the logarithm near 1, for which the caller takes the digits. + // https://github.com/asc-community/AngouriMath/issues/2675 + static (EDecimal Re, EDecimal V) ArcSinCosInner(Complex num, EContext context, bool cosine) { var (x, y) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); - var xp1 = x.Increment(); - var xm1 = x.Decrement(); - var rho = xp1.MultiplyAndAdd(xp1, y.Multiply(y, context), context).SqrtByIntegerRoot(context); - var sigma = xm1.MultiplyAndAdd(xm1, y.Multiply(y, context), context).SqrtByIntegerRoot(context); + var (ax, ay) = (x.Abs(), y.Abs()); + var axp1 = ax.Increment(); + var rho = Hypot(axp1, ay, context); + var sigma = Hypot(ax.Decrement(), ay, context); var alpha = rho.Add(sigma, context).Divide(2, context); - // beta is (|w + 1| - |w - 1|) / 2, in [-1, 1] by the triangle inequality and exactly 1 for a real w past - // 1; the two roots are rounded, and a beta of 1 + ε made arcsin(beta) NaN, as arcsin(6 + pi) was. - // https://github.com/asc-community/AngouriMath/issues/2244 - var beta = rho.Subtract(sigma, context).Divide(2, context); - if (beta.GreaterThan(EDecimal.One)) - beta = EDecimal.One; - else if (beta.LessThan(-EDecimal.One)) - beta = -EDecimal.One; - return (beta, - alpha.MultiplyAndSubtract(alpha, EDecimal.One, context).SqrtByIntegerRoot(context).Add(alpha, context).NaturalLogarithm(context).Multiply((y.IsNegative || y.IsZero) ? -1 : 1, context), - alpha); + var ySquared = ay.Multiply(ay, context); + // rho - (|x| + 1) is y^2 / (rho + |x| + 1), and sigma - | |x| - 1 | is y^2 / (sigma + | |x| - 1 |). + var rhoPast = ySquared.Divide(rho.Add(axp1, context), context); + EDecimal alphaPastX, alphaPastOne; + if (ax.CompareTo(EDecimal.One) <= 0) + { + var oneLessX = EDecimal.One.Subtract(ax, context); + alphaPastX = rhoPast.Add(sigma, context).Add(oneLessX, context).Divide(2, context); + alphaPastOne = rhoPast.Add(ySquared.Divide(sigma.Add(oneLessX, context), context), context).Divide(2, context); + } + else + { + var xLessOne = ax.Decrement(); + alphaPastX = rhoPast.Add(ySquared.Divide(sigma.Add(xLessOne, context), context), context).Divide(2, context); + alphaPastOne = rhoPast.Add(sigma, context).Add(xLessOne, context).Divide(2, context); + } + var root = alphaPastX.Multiply(alpha.Add(ax, context), context).SqrtByIntegerRoot(context); + var halfPi = InternalAMExtensions.ConstantCache.Lookup(context).HalfPi; + EDecimal re; + if (!cosine) + { + var angle = root.IsZero ? halfPi : ax.Divide(root, context).Arctan(context); + re = x.IsNegative ? angle.Negate() : angle; + } + else + { + var angle = ax.IsZero ? halfPi : root.Divide(ax, context).Arctan(context); + re = x.IsNegative ? InternalAMExtensions.ConstantCache.Lookup(context).Pi.Subtract(angle, context) : angle; + } + var v = alphaPastOne.Add(alphaPastOne.Multiply(alpha.Increment(), context).SqrtByIntegerRoot(context), context) + .Increment().NaturalLogarithm(context); + return (re, (y.IsNegative || y.IsZero) ? v.Negate() : v); } /// @@ -1283,16 +1344,27 @@ private static int DigitsBelowOne(EDecimal x, EDecimal y) /// private static Complex ArcSinOrCos(Complex num, EContext context, bool cosine) { - // beta is a difference of two moduli of the argument's size, known to the working digits of that size; - // past the reach that leaves none of it, and arcsin(10^5000) was 0. The infinity it was answers as before. - // https://github.com/asc-community/AngouriMath/issues/2668 - num = WithinTheSpecialFunctionsReach(num); var (x, y) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal); + if (x.IsNaN() || y.IsNaN()) + return Real.NaN; + // An infinite part leaves v infinite, and the real part the limit along the direction it goes off in, + // the diagonal where both parts are, as Arctan2 reads two infinities: arcsin(-oo) is -pi/2 - oo i, and + // arcsin(+oo i) is +oo i. https://github.com/asc-community/AngouriMath/issues/2675 + if (!x.IsFinite || !y.IsFinite) + { + var consts = InternalAMExtensions.ConstantCache.Lookup(context); + var turn = !y.IsFinite ? (!x.IsFinite ? consts.QuarterPi : EDecimal.Zero) : consts.HalfPi; + var real = cosine ? (x.IsNegative ? consts.Pi.Subtract(consts.HalfPi.Subtract(turn, context), context) : consts.HalfPi.Subtract(turn, context)) + : (x.IsNegative ? turn.Negate() : turn); + var infinity = (y.IsNegative || y.IsZero) != cosine ? EDecimal.NegativeInfinity : EDecimal.PositiveInfinity; + return Complex.Create(real, infinity); + } var work = Working(context, 10 + 2 * DigitsBelowOne(x, y)); - var (beta, v, alpha) = ArcSinCosInner(num, work); - var (re, im) = cosine ? (beta.Acos(work), v.Negate()) : (beta.Arcsin(work), v); - var scale = alpha.ScaleByPowerOfTen(context.Precision.ToInt32Checked() - work.Precision.ToInt32Checked()); - return Complex.CreateAtScales(re.RoundToPrecision(context), im.RoundToPrecision(context), scale, scale); + var (re, v) = ArcSinCosInner(num, work, cosine); + var im = cosine ? v.Negate() : v; + // Neither part cancels, so neither is a residual: arcsin(10^100) has the imaginary part -230.95, which + // against alpha, 10^100, was. https://github.com/asc-community/AngouriMath/issues/2675 + return Complex.CreateAtScales(re.RoundToPrecision(context), im.RoundToPrecision(context), EDecimal.Zero, EDecimal.Zero); } /// Calculates the exact value of arcsine of num diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs b/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs index 8a6dbee68..533c7b9ff 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Number/TrigonometricIntegrals.cs @@ -87,7 +87,10 @@ private static Complex TrigonometricIntegral(Complex z, bool hyperbolic, bool od if (!hyperbolic && z is not Rational && im.IsZero && re.CompareToTotalMagnitude(tenToTheEight) >= 0 && re.Exponent.Add(re.Precision()).CompareTo(context.Precision.Subtract(16)) > 0) return odd ? Real.Create(EDecimal.PI(context).Divide(re.IsNegative ? -2 : 2, context)) : Real.NaN; - var (valueRe, valueIm, reScale, imScale) = TrigonometricIntegral(re, im, hyperbolic, odd, context); + // The part the four oscillate along, exactly where it is an exact rational: Si(10^500) was NaN for + // want of the digits of cos(10^500). https://github.com/asc-community/AngouriMath/issues/2675 + var (along, alongIsExact) = PeriodicArgument(hyperbolic ? z.ImaginaryPart : z.RealPart, hyperbolic ? im : re, context); + var (valueRe, valueIm, reScale, imScale) = TrigonometricIntegral(hyperbolic ? re : along, hyperbolic ? along : im, hyperbolic, odd, context, alongIsExact); // On the axes, what is known exactly is given so: Si and Shi are real on the real line // and imaginary on the imaginary axis; Ci and Chi are real on the positive real axis, i pi // more on the negative, and i pi/2 sgn(y) more than a real value on the imaginary axis. @@ -112,12 +115,12 @@ private static Complex TrigonometricIntegral(Complex z, bool hyperbolic, bool od /// One of the four at re + i im, before any rounding back, and for each part the scale it is a /// residual against at 's precision. /// - private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) TrigonometricIntegral(EDecimal re, EDecimal im, bool hyperbolic, bool odd, EContext context) + private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) TrigonometricIntegral(EDecimal re, EDecimal im, bool hyperbolic, bool odd, EContext context, bool alongIsExact) { var precision = context.Precision.ToInt32Checked(); var modulus = Math.Sqrt(Math.Pow(re.ToDouble(), 2) + Math.Pow(im.ToDouble(), 2)); if (modulus > (precision + 5) * Math.Log(10)) - return ByTheExponentialIntegral(re, im, hyperbolic, odd, context); + return ByTheExponentialIntegral(re, im, hyperbolic, odd, context, alongIsExact); // The digits the terms cancel away from the axis the function grows along, and ten over. var growth = hyperbolic ? Math.Abs(re.ToDouble()) : Math.Abs(im.ToDouble()); var work = Working(context, (int)Math.Ceiling((modulus - growth) / Math.Log(10)) + 10); @@ -171,12 +174,16 @@ private static ((EDecimal Re, EDecimal Im) Sum, (EDecimal Re, EDecimal Im) Scale /// /// The four past the series' reach, from the exponential integral: see . /// - private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) ByTheExponentialIntegral(EDecimal re, EDecimal im, bool hyperbolic, bool odd, EContext context) + /// + /// says that the part the function oscillates along, the real for Si and + /// Ci and the imaginary for Shi and Chi, is exactly the number asked about. + /// + private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) ByTheExponentialIntegral(EDecimal re, EDecimal im, bool hyperbolic, bool odd, EContext context, bool alongIsExact) { if (!hyperbolic) { // Si(z) = -i Shi(i z), and Ci(z) = Chi(i z) + ln z - ln(i z): i z = -im + i re. - var (valueRe, valueIm, reScale, imScale) = ByTheExponentialIntegral(im.Negate(), re, hyperbolic: true, odd, context); + var (valueRe, valueIm, reScale, imScale) = ByTheExponentialIntegral(im.Negate(), re, hyperbolic: true, odd, context, alongIsExact); if (odd) // -i (a + i b) = b - i a return (valueIm, valueRe.Negate(), imScale, reScale); @@ -187,8 +194,8 @@ private static (EDecimal Re, EDecimal Im, EDecimal ReScale, EDecimal ImScale) By return (valueRe, valueIm.Add(branchTerm), reScale, imScale.Add(branchTerm.Abs())); } var work = Working(context, 10); - var (plusRe, plusIm, plusReScale, plusImScale) = Ei(re, im, context, extraDigits: 10); - var (minusRe, minusIm, minusReScale, minusImScale) = Ei(re.Negate(), im.Negate(), context, extraDigits: 10); + var (plusRe, plusIm, plusReScale, plusImScale) = Ei(re, im, context, extraDigits: 10, alongIsExact); + var (minusRe, minusIm, minusReScale, minusImScale) = Ei(re.Negate(), im.Negate(), context, extraDigits: 10, alongIsExact); var half = EDecimal.FromString("0.5"); var (sumRe, sumIm) = odd ? (plusRe.Subtract(minusRe, work).Multiply(half, work), plusIm.Subtract(minusIm, work).Multiply(half, work)) diff --git a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs index b0b887ea3..a337616b1 100644 --- a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs @@ -596,6 +596,64 @@ public void Issue2668_TheExponentialIntegralFarUpTheImaginaryAxisIsIPi() $"Ei(i exp(300)) is {value}"); } + // Past about 10^50 a complex path took a part for a residual against the size of the argument, which a sine, + // a cosine or arcsin's imaginary part never reaches: arcsin(10^100) lost its imaginary part, tanh(10^60 i) kept + // a real part of -2.2 that is 0, and Ci(10^50) was 0. And arcsin's real part was a difference of two moduli of + // the argument's size, with no digits left past 10^110: arcsin(10^200) was 0. Each part is held to a relative + // 1e-10 of mpmath's at 2000 digits, and a part that is 0 to 0; arcsin of a real past 1 is taken from below the + // axis, as the library takes it. https://github.com/asc-community/AngouriMath/issues/2675 + [Theory] + [InlineData("arcsin(10^100)", "1.57079632679489661923132169164", "-230.95165647996451371121637759")] + [InlineData("arcsin(10^200)", "1.57079632679489661923132169164", "-461.210165779369082113015523058")] + [InlineData("arcsin(10^500)", "1.57079632679489661923132169164", "-1151.98569367758278731841295946")] + [InlineData("arcsin(10^999)", "1.57079632679489661923132169164", "-2300.97565508161158364339069535")] + [InlineData("arcsin(-10^500)", "-1.57079632679489661923132169164", "-1151.98569367758278731841295946")] + [InlineData("arcsin(10^100 * i)", "0", "230.95165647996451371121637759")] + [InlineData("arccos(10^500)", "0", "1151.98569367758278731841295946")] + [InlineData("arccos(10^100 * i)", "1.57079632679489661923132169164", "-230.95165647996451371121637759")] + [InlineData("arccos(-10^200)", "3.14159265358979323846264338328", "461.210165779369082113015523058")] + [InlineData("arcsin(10^1500)", "1.57079632679489661923132169164", "-3454.57078667162847133640441415")] + [InlineData("arccos(10^1500 * i)", "1.57079632679489661923132169164", "-3454.57078667162847133640441415")] + [InlineData("tanh(10^60 * i)", "0", "-1.4903359261613561946874765172")] + [InlineData("tanh(10^50 * i)", "0", "1.28709970950297036450135358364")] + [InlineData("coth(10^50 * i)", "0", "-0.7769405840252753186326085493")] + [InlineData("e^(10^60 * i)", "-0.557182948248566708972916420591", "0.830389765219342664664061785421")] + [InlineData("sin(10^60 + i)", "1.2813583660587445178598677057", "-0.654802065859688050757503200314")] + [InlineData("cos(10^60 + i)", "-0.859778217491627438906842228781", "-0.975875043275367546817436179076")] + [InlineData("Ci(10^50)", "-7.89672493429310082710289539917E-51", "0")] + [InlineData("Ci(10^100)", "-3.72376123661276688262086695553E-101", "0")] + [InlineData("Ci(10^500)", "3.11026930907900280476371099337E-501", "0")] + [InlineData("Si(10^500)", "1.57079632679489661923132169164", "0")] + [InlineData("Ei(10^50 * i)", "-7.89672493429310082710289539917E-51", "3.14159265358979323846264338328")] + [InlineData("Ei(-10^60 * i)", "8.30389765219342664664061785421E-61", "-3.14159265358979323846264338328")] + [InlineData("sqrt(10^50 + i)", "1.0E+25", "5.0E-26")] + public void Issue2675_ALargeArgumentKeepsEveryPartOfItsValue(string expression, string trueReal, string trueImaginary) + { + var value = Assert.IsAssignableFrom(expression.ToEntity().Evaled); + foreach (var (part, truth) in new[] { (value.RealPart.EDecimal, trueReal), (value.ImaginaryPart.EDecimal, trueImaginary) }) + { + var expected = EDecimal.FromString(truth); + Assert.True(part.IsFinite && part.Subtract(expected).Abs().CompareTo(expected.Abs().Multiply(EDecimal.FromString("1E-10"))) <= 0, + $"{expression} is {value}, where it is {trueReal} + {trueImaginary}i"); + } + } + + // An infinite part leaves arcsin's imaginary part infinite and its real part the limit along the direction the + // argument goes off in: arcsin(-oo) was pi/2 - oo i, where arcsin(-x) for a real x past 1 is -pi/2 - i arcosh x. + // https://github.com/asc-community/AngouriMath/issues/2675 + [Theory] + [InlineData("arcsin(-oo)", "-pi/2", "-oo")] + [InlineData("arcsin(+oo)", "pi/2", "-oo")] + [InlineData("arccos(-oo)", "pi", "+oo")] + [InlineData("arcsin(+oo * i)", "0", "+oo")] + public void Issue2675_AnArcsineOfAnInfinityGoesOffAlongItsDirection(string expression, string real, string imaginary) + { + var value = Assert.IsAssignableFrom(expression.ToEntity().Evaled); + var expectedReal = Assert.IsAssignableFrom(real.ToEntity().Evaled).EDecimal; + Assert.True(value.RealPart.EDecimal.Subtract(expectedReal).Abs().CompareTo(EDecimal.FromString("1E-50")) <= 0, $"{expression} is {value}"); + Assert.Equal(Assert.IsAssignableFrom(imaginary.ToEntity().Evaled).EDecimal, value.ImaginaryPart.EDecimal); + } + // A rational root of an exact number is that root only where its power is the number exactly: one // within 1e-16 of it was taken, so the square root of 9 + 4/10^24 was 3, which made the quadratic // x^2 - 3x - 1/10^24 lose both its roots. The differences are worked out in mpmath at eighty digits.