While independently testing Swift Numerics main at commit 899af71c0256d0ad181e3b7eb3453c1065d928a5, I found that the overflow-avoiding fast paths for Complex.cosh and Complex.sinh return the wrong sign for one component when the real part is sufficiently large and negative. The error also propagates to Complex.cos and Complex.sin.
This is a component-sign/quadrant error, rather than an accuracy-at-the-last-bit issue.
Minimal reproducer
import ComplexModule
typealias C = Complex<Double>
print(C.cosh(C(-40, 0.5)))
print(C.sinh(C(-40, 0.5)))
print(C.cos(C(0.5, 40)))
print(C.sin(C(0.5, 40)))
Observed:
cosh(-40 + 0.5i) = ( 1.032850027510405e+17, 5.642485416641618e+16)
sinh(-40 + 0.5i) = (-1.032850027510405e+17, -5.642485416641618e+16)
cos( 0.5 + 40i) = ( 1.032850027510405e+17, 5.642485416641618e+16)
sin( 0.5 + 40i) = (-5.642485416641618e+16, 1.032850027510405e+17)
Expected:
cosh(-40 + 0.5i) = ( 1.032850027510405e+17, -5.642485416641618e+16)
sinh(-40 + 0.5i) = (-1.032850027510405e+17, 5.642485416641618e+16)
cos( 0.5 + 40i) = ( 1.032850027510405e+17, -5.642485416641618e+16)
sin( 0.5 + 40i) = ( 5.642485416641618e+16, 1.032850027510405e+17)
The observed results violate the exact identities
cosh(-x + iy) = conjugate(cosh(x + iy))
sinh(-x + iy) = -conjugate(sinh(x + iy))
and an independent 80-decimal-digit mpmath evaluation gives the expected signs.
In the large-abs(x) branches, both real hyperbolic factors are approximated using exp(abs(x))/2. For negative x, however, only the sinh(x) factor is odd. For Double, the affected path begins near abs(real) = 36.04. The existing near-overflow tests also appear to encode the same incorrect negative-input signs.
A possible fix direction is to use sx = sign(x) and form the phase factors as:
cosh: (cos(y), sx * sin(y))
sinh: (sx * cos(y), sin(y))
The two-step overflow-avoiding scaling can remain unchanged.
I filed the focused upstream report as issue #347. An executable reproducer and the broader contract audit are available in the audit repository.
I would appreciate review of the analysis and proposed fix direction.