| 885 | // arctan(1/z) = 1/z + O(1/z³), with |z|/4 against an overflow of |z|. |
| 886 | const h4 = Math.hypot(x / 4, y / 4); |
| 887 | return new Complex(x / 16 / h4 / h4 + shift, -y / 16 / h4 / h4); |
| 888 | } |
| 889 | // arctan(1/z) = (i/2)·ln((z − i)/(z + i)), and its imaginary part is the |
| 890 | // imaginary part of arccot z. |
| 891 | // Im: ¼·ln(|z − i|²/|z + i|²) = −¼·ln(1 + 4y/|z − i|²), computed for |y| |
| 892 | // (as the real part in `atanhCore()`). |
| 893 | const ay = Math.abs(y); |
| 894 | const u = 1 - ay; |
| 895 | const d = x * x + u * u; |
| 896 | const im = |
| 897 | d < 1e-290 |
| 898 | ? 0.5 * (Math.log(Math.hypot(x, 1 + ay)) - Math.log(Math.hypot(x, u))) |
| 899 | : 0.25 * Math.log1p((4 * ay) / d); |
| 900 | const imaginary = signBit(y) ? im : -im; |
| 901 | // On the imaginary axis: π/2 − arctan(iy) has the real part π/2 from −i |
| 902 | // to i (the poles included), and the side of the cut of `complexAtan()` |
| 903 | // beyond them. |
| 904 | if (x === 0) return new Complex(ay <= 1 ? Math.PI / 2 : shift, imaginary); |
| 905 | // Re of arctan(1/z): −½·arg((z − i)·conj(z + i)) = ½·atan2(2x, |z|² − 1). |
| 906 | // |z|² − 1 is computed from the larger part, whose difference with 1 is |
| 907 | // exact. |
| 908 | const ax = Math.abs(x); |
| 909 | const m = |
| 910 | ay >= ax ? x * x + (ay - 1) * (ay + 1) : (ax - 1) * (ax + 1) + y * y; |
| 911 | return new Complex(0.5 * Math.atan2(2 * x, m) + shift, imaginary); |
| 912 | } |
| 913 | |
| 914 | /** cos(πx) and sin(πx) with the argument reduced exactly before the |
| 915 | * multiplication by π. `Math.sin(Math.PI * x)` loses relative accuracy |
| 916 | * near every integer x (Math.PI·x is rounded, and sin is steep there |
| 917 | * relative to its value), and `Math.cos(Math.PI / 2)` is 6e-17, not 0. |
| 918 | * Here x is reduced to x = t + q/2 with |t| ≤ 1/4 (both steps are exact in |
| 919 | * floating point), so the values are exact at multiples of 1/2 and |
| 920 | * accurate to a few ulps elsewhere. A zero part is `+0`, never `−0` |
| 921 | * (`1/sin(π)` would otherwise be `−∞`). */ |
| 922 | export function cosSinPi(x: number): [number, number] { |
| 923 | const r = x - 2 * Math.round(x / 2); // r ∈ [−1, 1], same angle |
| 924 | const q = Math.round(2 * r); // −2 … 2 |
| 925 | const t = r - q / 2; // |t| ≤ 1/4 |
| 926 | return quarterTurns(q, t); |
| 927 | } |
| 928 | |
| 929 | /** The correctly rounded double of `√3/2` (`cos(π/6)`). */ |
| 930 | const SQRT3_2 = Math.sqrt(3) / 2; |
| 931 | |
| 932 | /** |
| 933 | * cos(πx) and sin(πx) for `x = q/2 + t`, with `q` an integer and |
| 934 | * `|t| ≤ 1/4`. At `|t| = 1/4` and `|t| = 1/6` the values are the correctly |
| 935 | * rounded doubles of `√2/2`, `√3/2` and `1/2` (`Math.sin(Math.PI / 6)` is |
| 936 | * `0.49999999999999994`). A zero part is `+0`. |