| 22 | // compiled JavaScript) also contains this module, so the call runs when it |
| 23 | // loads. |
| 24 | installComplexScaling(); |
| 25 | |
| 26 | // Lanczos approximation coefficients (g = 7, n = 9), accurate to ~15 digits |
| 27 | // for the principal branch. See Numerical Recipes / mathjs gamma(). |
| 28 | const LANCZOS_G = 7; |
| 29 | const LANCZOS_P = [ |
| 30 | 0.99999999999980993, 676.5203681218851, -1259.1392167224028, |
| 31 | 771.32342877765313, -176.61502916214059, 12.507343278686905, |
| 32 | -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7, |
| 33 | ]; |
| 34 | |
| 35 | /** |
| 36 | * `x · 2^k` for an integer `k` of any size. The factor is applied in steps, |
| 37 | * because `2^k` is a double only for `-1074 <= k <= 1023`. Each step is |
| 38 | * exact while the result stays in the normal range of a double. |
| 39 | */ |
| 40 | function scaleByPowerOfTwo(x: number, k: number): number { |
| 41 | // A shift past the whole range of a double has a known result, and the |
| 42 | // loops below would take one step per 1022 units of `k`: a scaled value |
| 43 | // with an exponent near −9e20 (the cot-derivative term of a polygamma at |
| 44 | // Im(z) = 1e20) made `PolyGamma(1, −5 + 10²⁰i)` run for minutes, and an |
| 45 | // infinite `k` never ended. The smallest subnormal is 2^−1074 and the |
| 46 | // largest double is below 2^1024, so a mantissa below 2^1024 times 2^k is |
| 47 | // 0 for k < −2200 and ±∞ for k > 2100 (the sign of x is kept). |
| 48 | if (x === 0 || Number.isNaN(x)) return x; |