| 302 | // |
| 303 | // The functions below use the formulas of W. Kahan, "Branch Cuts for Complex |
| 304 | // Elementary Functions, or Much Ado About Nothing's Sign Bit" (1987). They |
| 305 | // take products of two square roots in place of `√(1 − z²)`, so there is no |
| 306 | // cancellation and no overflow below `|z| ≈ 10³⁰⁷`, and they keep the |
| 307 | // relative accuracy of both parts. |
| 308 | // |
| 309 | // The "core" functions follow the sign of a zero part to pick the side of a |
| 310 | // branch cut (IEEE 754 and C99 conventions). The engine does not keep the |
| 311 | // sign of a zero, so the exported functions first give a zero part the sign |
| 312 | // that selects the side the engine uses on each cut. That side is the one of |
| 313 | // mpmath and of Mathematica ("counter-clockwise continuity"): |
| 314 | // - `arcsin`, `arccos`, `artanh` on the real axis: for `x > 1` the side |
| 315 | // below the axis, for `x < −1` the side above it (`arcsin 2` is |
| 316 | // `π/2 − 1.317i`, `artanh 2` is `0.549 − (π/2)i`). |
| 317 | // - `arcosh` on the real axis (`x < 1`): the side above the axis |
| 318 | // (`arcosh(−2)` is `1.317 + πi`). |
| 319 | // - `arsinh` on the imaginary axis: for `y > 1` the side right of the axis, |
| 320 | // for `y < −1` the side left of it (`arsinh 2i` is `1.317 + (π/2)i`, |
| 321 | // `arsinh(−2i)` is `−1.317 − (π/2)i`). |
| 322 | // - `arctan` on the imaginary axis: for `y > 1` the side right of the axis, |
| 323 | // for `y < −1` the side left of it (`arctan 2i` is `π/2 + 0.549i`, |
| 324 | // `arctan(−2i)` is `−π/2 − 0.549i`), so `arctan(−z) = −arctan(z)` on the |
| 325 | // cut. This is the side that `arctan z = −i·artanh(iz)` gives with the |
| 326 | // side of `artanh` above. |
| 327 | // A value with an infinite or NaN part uses the `complex.js` method. |
| 328 | // |
| 329 | |
| 330 | /** True if `x` is `−0` or negative. */ |
| 331 | function signBit(x: number): boolean { |
| 332 | return x < 0 || Object.is(x, -0); |
| 333 | } |
| 334 | |
| 335 | /** |
| 336 | * The principal square root of `x + iy`, with the sign of a zero imaginary |
| 337 | * part kept (`√(−4 − 0i)` is `−2i`). The operands are scaled when they are |