NumericAL
A header-only C++20 lexer built on REAL
Loading...
Searching...
No Matches
complex_math.hpp
Go to the documentation of this file.
1
12#ifndef NUMERICAL_COMPLEX_MATH_HPP
13#define NUMERICAL_COMPLEX_MATH_HPP
14
15#include <algorithm>
16#include <array>
17#include <cmath>
18#include <complex>
19#include <concepts>
20#include <cstddef>
21#include <limits>
22#include <numbers>
23
24// A function kept out of its callers, in the spelling each compiler takes.
25#if !defined(NUMERICAL_OUT_OF_LINE)
26# if defined(_MSC_VER) && !defined(__clang__)
27# define NUMERICAL_OUT_OF_LINE __declspec(noinline)
28# else
29# define NUMERICAL_OUT_OF_LINE [[gnu::noinline]] // NOLINT(cppcoreguidelines-macro-usage): an attribute, which no function can stand for
30# endif
31#endif
32
33namespace numerical::detail {
34
36 template <std::floating_point R>
37 inline constexpr R exp_bound {static_cast<R>(static_cast<int>(static_cast<R>(std::numeric_limits<R>::max_exponent - 1) * std::numbers::ln2_v<R>))};
38
40 template <std::floating_point R>
41 inline constexpr R half_exp_bound {static_cast<R>(static_cast<int>(static_cast<R>(std::numeric_limits<R>::max_exponent - 1) * std::numbers::ln2_v<R> / R {2}))};
42
47 inline void sine_and_cosine(double x,
48 double& sine,
49 double& cosine)
50 {
51#if defined(__GLIBC__)
52 ::sincos(x, &sine, &cosine);
53#elif defined(__APPLE__)
54 ::__sincos(x, &sine, &cosine);
55#else
56 sine = std::sin(x);
57 cosine = std::cos(x);
58#endif
59 }
60
62 inline void sine_and_cosine(float x,
63 float& sine,
64 float& cosine)
65 {
66#if defined(__GLIBC__)
67 ::sincosf(x, &sine, &cosine);
68#elif defined(__APPLE__)
69 ::__sincosf(x, &sine, &cosine);
70#else
71 sine = std::sin(x);
72 cosine = std::cos(x);
73#endif
74 }
75
79 template <std::floating_point R>
81 {
82 return std::sin(x);
83 }
84
86 template <std::floating_point R>
88 {
89 return std::cos(x);
90 }
91
99#if !defined(__aarch64__) && !defined(_M_ARM64)
100 [[nodiscard]] inline bool libm_fuses() noexcept
101 {
102# if defined(__GLIBC__) && defined(_GLIBCXX_USE_C99_COMPLEX) && _GLIBCXX_USE_C99_COMPLEX
103 static const bool fused {[] {
104 const volatile double re {0.00028503236970950325}; // read at run time: no folding of the call
105 const volatile double im {-0.7408643619401744};
106 const std::complex<double> z {re, im};
107 const std::complex<double> answer {std::tan(z)}; // libstdc++'s: glibc's ctan
108 double sine {};
109 double cosine {};
110 sine_and_cosine(z.real(), sine, cosine);
111 const double sinh_y {std::sinh(z.imag())};
112 const double den {std::fma(sinh_y, sinh_y, cosine * cosine)};
113 return answer == std::complex<double> {(sine * cosine) / den, (sinh_y * std::cosh(z.imag())) / den};
114 }()};
115 return fused;
116# else
117 return false;
118# endif
119 }
120
121#endif
122
125 template <std::floating_point R>
127 R b,
128 R c,
129 R d)
130 {
131 const R second {c * d};
132#if defined(__aarch64__) || defined(_M_ARM64)
133 return std::fma(a, b, second);
134#else
135 if (libm_fuses()) {
136 return std::fma(a, b, second);
137 }
138 const R first {a * b};
139 return first + second;
140#endif
141 }
142
144 template <std::floating_point R>
146 R a,
147 R b)
148 {
149#if defined(__aarch64__) || defined(_M_ARM64)
150 return std::fma(a, b, s);
151#else
152 if (libm_fuses()) {
153 return std::fma(a, b, s);
154 }
155 const R product {a * b};
156 return s + product;
157#endif
158 }
159
162 template <std::floating_point R>
163 void small_sincos(R x,
164 R& sine,
165 R& cosine)
166 {
167 if (std::abs(x) > std::numeric_limits<R>::min()) {
169 return;
170 }
171 sine = x;
172 cosine = R {1};
173 }
174
179 template <std::floating_point R>
180 [[nodiscard]] std::complex<R> complex_exp(const std::complex<R>& z)
181 {
182 constexpr R inf {std::numeric_limits<R>::infinity()};
183 constexpr R nan {std::numeric_limits<R>::quiet_NaN()};
184 R x {z.real()};
185 const R y {z.imag()};
186 if (std::isfinite(x)) {
187 if (!std::isfinite(y)) {
188 return {nan, nan};
189 }
190 R sine {};
191 R cosine {};
193 constexpr R bound {exp_bound<R>};
194 if (x > bound) {
195 const R step {std::exp(bound)};
196 x -= bound;
197 sine *= step;
198 cosine *= step;
199 if (x > bound) {
200 x -= bound;
201 sine *= step;
202 cosine *= step;
203 }
204 }
205 if (x > bound) { // past three bounds: it overflows
206 return {std::numeric_limits<R>::max() * cosine, std::numeric_limits<R>::max() * sine};
207 }
208 const R scale {std::exp(x)};
209 return {scale * cosine, scale * sine};
210 }
211 if (std::isinf(x)) {
212 if (std::isfinite(y)) {
213 const R magnitude {std::signbit(x) ? R {0} : inf};
214 if (y == R {0}) {
215 return {magnitude, y};
216 }
217 return {std::copysign(magnitude, std::cos(y)), std::copysign(magnitude, std::sin(y))};
218 }
219 if (!std::signbit(x)) {
220 return {inf, y - y};
221 }
222 return {R {0}, std::copysign(R {0}, y)};
223 }
224 if (y == R {0}) {
225 return {nan, y};
226 }
227 return {nan, nan};
228 }
229
234 template <std::floating_point R>
235 [[nodiscard]] std::complex<R> complex_cosh(const std::complex<R>& z)
236 {
237 constexpr R inf {std::numeric_limits<R>::infinity()};
238 constexpr R nan {std::numeric_limits<R>::quiet_NaN()};
239 const R x {z.real()};
240 const R y {z.imag()};
241 if (std::isfinite(x)) {
242 if (!std::isfinite(y)) {
243 return {y - y, x == R {0} ? R {0} : nan};
244 }
245 R sine {};
246 R cosine {};
248 constexpr R bound {exp_bound<R>};
249 if (std::abs(x) > bound) {
250 const R step {std::exp(bound)};
251 R rx {std::abs(x)};
252 if (std::signbit(x)) {
253 sine = -sine;
254 }
255 rx -= bound;
256 sine *= step / R {2};
257 cosine *= step / R {2};
258 if (rx > bound) {
259 rx -= bound;
260 sine *= step;
261 cosine *= step;
262 }
263 if (rx > bound) {
264 return {std::numeric_limits<R>::max() * cosine, std::numeric_limits<R>::max() * sine};
265 }
266 const R scale {std::exp(rx)};
267 return {scale * cosine, scale * sine};
268 }
269 return {std::cosh(x) * cosine, std::sinh(x) * sine};
270 }
271 if (std::isinf(x)) {
272 if (std::isfinite(y) && y != R {0}) {
273 return {std::copysign(inf, std::cos(y)), std::copysign(inf, std::sin(y)) * std::copysign(R {1}, x)};
274 }
275 if (y == R {0}) {
276 return {inf, y * std::copysign(R {1}, x)};
277 }
278 return {inf, y - y};
279 }
280 return {nan, y == R {0} ? y : nan};
281 }
282
287 template <std::floating_point R>
288 [[nodiscard]] std::complex<R> complex_sinh(const std::complex<R>& z)
289 {
290 constexpr R inf {std::numeric_limits<R>::infinity()};
291 constexpr R nan {std::numeric_limits<R>::quiet_NaN()};
292 const bool negative {std::signbit(z.real())};
293 const R x {std::abs(z.real())};
294 const R y {z.imag()};
295 if (std::isfinite(x)) {
296 if (!std::isfinite(y)) {
297 if (x == R {0}) {
298 return {negative ? R {-0.0} : R {0}, y - y};
299 }
300 return {nan, nan};
301 }
302 R sine {};
303 R cosine {};
305 if (negative) {
306 cosine = -cosine;
307 }
308 constexpr R bound {exp_bound<R>};
309 if (x > bound) {
310 const R step {std::exp(bound)};
311 R rx {x - bound};
312 sine *= step / R {2};
313 cosine *= step / R {2};
314 if (rx > bound) {
315 rx -= bound;
316 sine *= step;
317 cosine *= step;
318 }
319 if (rx > bound) {
320 return {std::numeric_limits<R>::max() * cosine, std::numeric_limits<R>::max() * sine};
321 }
322 const R scale {std::exp(rx)};
323 return {scale * cosine, scale * sine};
324 }
325 return {std::sinh(x) * cosine, std::cosh(x) * sine};
326 }
327 if (std::isinf(x)) {
328 if (std::isfinite(y) && y != R {0}) {
329 R sine {};
330 R cosine {};
332 const R re {std::copysign(inf, cosine)};
333 return {negative ? -re : re, std::copysign(inf, sine)};
334 }
335 if (y == R {0}) {
336 return {negative ? -inf : inf, y};
337 }
338 return {inf, y - y};
339 }
340 return {nan, y == R {0} ? y : nan};
341 }
342
344 template <std::floating_point R>
345 [[nodiscard]] std::complex<R> complex_cos(const std::complex<R>& z)
346 {
347 return complex_cosh(std::complex<R> {-z.imag(), z.real()});
348 }
349
354 template <std::floating_point R>
355 [[nodiscard]] std::complex<R> complex_sin(const std::complex<R>& z)
356 {
357 constexpr R inf {std::numeric_limits<R>::infinity()};
358 constexpr R nan {std::numeric_limits<R>::quiet_NaN()};
359 const bool negative {std::signbit(z.real())};
360 const R x {std::abs(z.real())};
361 const R y {z.imag()};
362 if (std::isfinite(y)) {
363 if (!std::isfinite(x)) {
364 if (y == R {0}) {
365 return {x - x, y};
366 }
367 return {nan, nan};
368 }
369 R sine {};
370 R cosine {};
372 if (negative) {
373 sine = -sine;
374 }
375 constexpr R bound {exp_bound<R>};
376 if (std::abs(y) > bound) {
377 const R step {std::exp(bound)};
378 R iy {std::abs(y) - bound};
379 if (std::signbit(y)) {
380 cosine = -cosine;
381 }
382 sine *= step / R {2};
383 cosine *= step / R {2};
384 if (iy > bound) {
385 iy -= bound;
386 sine *= step;
387 cosine *= step;
388 }
389 if (iy > bound) {
390 return {std::numeric_limits<R>::max() * sine, std::numeric_limits<R>::max() * cosine};
391 }
392 const R scale {std::exp(iy)};
393 return {scale * sine, scale * cosine};
394 }
395 return {std::cosh(y) * sine, std::sinh(y) * cosine};
396 }
397 if (std::isinf(y)) {
398 if (x == R {0}) {
399 return {negative ? R {-0.0} : R {0}, y};
400 }
401 if (std::isfinite(x)) {
402 R sine {};
403 R cosine {};
405 const R re {std::copysign(inf, sine)};
406 const R im {std::copysign(inf, cosine)};
407 return {negative ? -re : re, std::signbit(y) ? -im : im};
408 }
409 return {x - x, inf};
410 }
411 return {x == R {0} ? (negative ? R {-0.0} : R {0}) : nan, nan};
412 }
413
418 template <std::floating_point R>
419 [[nodiscard]] std::complex<R> complex_tanh(const std::complex<R>& z)
420 {
421 constexpr R nan {std::numeric_limits<R>::quiet_NaN()};
422 const R x {z.real()};
423 const R y {z.imag()};
424 if (!std::isfinite(x) || !std::isfinite(y)) {
425 if (std::isinf(x)) {
426 if (std::isfinite(y) && std::abs(y) > R {1}) {
427 const R product {std::sin(y) * std::cos(y)};
428 return {std::copysign(R {1}, x), std::copysign(R {0}, product)};
429 }
430 return {std::copysign(R {1}, x), std::copysign(R {0}, y)};
431 }
432 if (y == R {0}) {
433 return z;
434 }
435 return {x == R {0} ? x : nan, nan};
436 }
437 R sine {};
438 R cosine {};
440 constexpr R bound {half_exp_bound<R>};
441 if (std::abs(x) > bound) {
442 const R step {std::exp(R {2} *bound)};
443 R im {R {4} *sine};
444 im *= cosine;
445 R rx {std::abs(x) - bound};
446 im /= step;
447 if (rx > bound) { // the imaginary part underflows
448 im /= step;
449 }
450 else {
451 im /= std::exp(R {2} *rx);
452 }
453 return {std::copysign(R {1}, x), im};
454 }
455 R sinh_x {x};
456 R cosh_x {1};
457 if (std::abs(x) > std::numeric_limits<R>::min()) {
458 sinh_x = std::sinh(x);
459 cosh_x = std::cosh(x);
460 }
461 R den {cosine * cosine};
462 if (std::abs(sinh_x) > std::abs(cosine) * std::numeric_limits<R>::epsilon()) {
464 }
465 const R re {sinh_x * cosh_x};
466 const R im {sine * cosine};
467 return {re / den, im / den};
468 }
469
474 template <std::floating_point R>
475 [[nodiscard]] std::complex<R> complex_tan(const std::complex<R>& z)
476 {
477 constexpr R nan {std::numeric_limits<R>::quiet_NaN()};
478 const R x {z.real()};
479 const R y {z.imag()};
480 if (!std::isfinite(x) || !std::isfinite(y)) {
481 if (std::isinf(y)) {
482 if (std::isfinite(x) && std::abs(x) > R {1}) {
483 const R product {std::sin(x) * std::cos(x)};
484 return {std::copysign(R {0}, product), std::copysign(R {1}, y)};
485 }
486 return {std::copysign(R {0}, x), std::copysign(R {1}, y)};
487 }
488 if (x == R {0}) {
489 return z;
490 }
491 return {nan, y == R {0} ? y : nan};
492 }
493 R sine {};
494 R cosine {};
496 constexpr R bound {half_exp_bound<R>};
497 if (std::abs(y) > bound) {
498 const R step {std::exp(R {2} *bound)};
499 R re {R {4} *sine};
500 re *= cosine;
501 R iy {std::abs(y) - bound};
502 re /= step;
503 if (iy > bound) { // the real part underflows
504 re /= step;
505 }
506 else {
507 re /= std::exp(R {2} *iy);
508 }
509 return {re, std::copysign(R {1}, y)};
510 }
511 R sinh_y {y};
512 R cosh_y {1};
513 if (std::abs(y) > std::numeric_limits<R>::min()) {
514 sinh_y = std::sinh(y);
515 cosh_y = std::cosh(y);
516 }
517 R den {cosine * cosine};
518 if (std::abs(sinh_y) > std::abs(cosine) * std::numeric_limits<R>::epsilon()) {
520 }
521 const R re {sine * cosine};
522 const R im {sinh_y * cosh_y};
523 return {re / den, im / den};
524 }
525
531 [[nodiscard]] inline double unit_circle_offset(double x,
532 double y)
533 {
534 std::array<double, 5> terms {};
535 terms[1] = x * x;
536 terms[0] = std::fma(x, x, -terms[1]);
537 terms[3] = y * y;
538 terms[2] = std::fma(y, y, -terms[3]);
539 terms[4] = -1.0;
540 const auto by_magnitude_from {[&terms](std::size_t first) { // insertion, five terms at most
541 for (std::size_t i {first + 1}; i < terms.size(); ++i) {
542 const double term {terms[i]};
543 std::size_t j {i};
544 while (j > first && std::abs(terms[j - 1]) > std::abs(term)) {
545 terms[j] = terms[j - 1];
546 --j;
547 }
548 terms[j] = term;
549 }
550 }};
552 for (std::size_t i {0}; i <= 3; ++i) {
553 const double sum {terms[i + 1] + terms[i]};
554 const double error {(terms[i + 1] - sum) + terms[i]};
555 terms[i + 1] = sum;
556 terms[i] = error;
557 by_magnitude_from(i + 1);
558 }
559 double total {terms[4] + terms[3]};
560 total += terms[2];
561 total += terms[1];
562 total += terms[0];
563 return total;
564 }
565
567 [[nodiscard]] inline float unit_circle_offset(float x,
568 float y)
569 {
570 const double wide_x {static_cast<double>(x)};
571 const double wide_y {static_cast<double>(y)};
572 return static_cast<float>(libm_sum_of_products(wide_x - 1.0, wide_x + 1.0, wide_y, wide_y));
573 }
574
576 template <std::floating_point R>
578 R y)
579 {
580 return libm_sum_of_products(x, x, y, y) >= R {0.5};
581 }
582
588 template <std::floating_point R>
589 [[nodiscard]] std::complex<R> complex_log(const std::complex<R>& z)
590 {
591 constexpr R inf {std::numeric_limits<R>::infinity()};
592 constexpr R nan {std::numeric_limits<R>::quiet_NaN()};
593 const R x {z.real()};
594 const R y {z.imag()};
595 if (x == R {0} && y == R {0}) {
596 const R angle {std::signbit(x) ? std::numbers::pi_v<R> : R {0}};
597 return {-R {1} / std::abs(x), std::copysign(angle, y)};
598 }
599 if (std::isnan(x) || std::isnan(y)) {
600 return {std::isinf(x) || std::isinf(y) ? inf : nan, nan};
601 }
602 R larger {std::abs(x)};
603 R smaller {std::abs(y)};
604 int scale {0};
605 if (larger < smaller) {
606 std::swap(larger, smaller);
607 }
608 constexpr R least {std::numeric_limits<R>::min()};
609 if (larger > std::numeric_limits<R>::max() / R {2}) {
610 scale = -1;
611 larger = std::ldexp(larger, scale);
612 smaller = smaller >= least * R {2} ? std::ldexp(smaller, scale) : R {0};
613 }
614 else if (larger < least) { // the smaller part too
615 scale = std::numeric_limits<R>::digits;
616 larger = std::ldexp(larger, scale);
617 smaller = std::ldexp(smaller, scale);
618 }
619 R re {};
620 if (larger == R {1}) { // scaled, the larger part is far from 1: these four branches take scale 0
621 const R square {smaller * smaller};
622 re = std::log1p(square) / R {2};
623 }
624 else if (larger > R {1} && larger < R {2} && smaller < R {1}) {
625 R offset {(larger - R {1}) * (larger + R {1})};
626 if (smaller >= std::numeric_limits<R>::epsilon()) {
627 offset = libm_add_product(offset, smaller, smaller);
628 }
629 re = std::log1p(offset) / R {2};
630 }
631 else if (larger < R {1} && larger >= R {0.5} && smaller < std::numeric_limits<R>::epsilon() / R {2}) {
632 const R offset {(larger - R {1}) * (larger + R {1})};
633 re = std::log1p(offset) / R {2};
634 }
635 else if (larger < R {1} && larger >= R {0.5} && unit_circle_squares_reach_half(larger, smaller)) {
636 re = std::log1p(unit_circle_offset(larger, smaller)) / R {2};
637 }
638 else {
639 const R correction {static_cast<R>(scale) * std::numbers::ln2_v<R>};
640 re = std::log(std::hypot(larger, smaller)) - correction;
641 }
642 return {re, std::atan2(y, x)};
643 }
644
653 template <std::floating_point R>
654 [[nodiscard]] std::complex<R> complex_sqrt(const std::complex<R>& z)
655 {
656 constexpr R inf {std::numeric_limits<R>::infinity()};
657 constexpr R nan {std::numeric_limits<R>::quiet_NaN()};
658 constexpr R least {std::numeric_limits<R>::min()};
659 constexpr R half {0.5};
660 R x {z.real()};
661 R y {z.imag()};
662 if (std::isinf(y)) {
663 return {inf, y};
664 }
665 if (std::isinf(x)) {
666 if (x < R {0}) {
667 return {std::isnan(y) ? nan : R {0}, std::copysign(inf, y)};
668 }
669 return {x, std::isnan(y) ? nan : std::copysign(R {0}, y)};
670 }
671 if (std::isnan(x) || std::isnan(y)) {
672 return {nan, nan};
673 }
674 if (y == R {0}) {
675 if (x < R {0}) {
676 return {R {0}, std::copysign(std::sqrt(-x), y)};
677 }
678 return {std::abs(std::sqrt(x)), y};
679 }
680 if (x == R {0}) {
681 const R part {std::abs(y) >= R {2} *least ? std::sqrt(half * std::abs(y)) : half * std::sqrt(R {2} *std::abs(y))};
682 return {part, std::copysign(part, y)};
683 }
684 int scale {0};
685 if (std::abs(x) > std::numeric_limits<R>::max() / R {4}) {
686 scale = 1;
687 x = std::ldexp(x, -2);
688 y = std::ldexp(y, -2);
689 }
690 else if (std::abs(y) > std::numeric_limits<R>::max() / R {4}) {
691 scale = 1;
692 x = std::abs(x) >= R {4} *least ? std::ldexp(x, -2) : R {0};
693 y = std::ldexp(y, -2);
694 }
695 else if (std::abs(x) < R {2} *least && std::abs(y) < R {2} *least) {
696 scale = -((std::numeric_limits<R>::digits + 1) / 2);
697 x = std::ldexp(x, -2 * scale);
698 y = std::ldexp(y, -2 * scale);
699 }
700 const R modulus {std::hypot(x, y)};
701 R re {};
702 R im {};
703 if (x > R {0}) { // re from |z| + x, im = y / (2 re): no cancellation
704 re = std::sqrt(half * (modulus + x));
705 if (scale == 1 && std::abs(y) < R {1}) {
706 im = y / re;
707 re = std::ldexp(re, scale);
708 scale = 0;
709 }
710 else {
711 im = half * (y / re);
712 }
713 }
714 else { // im from |z| − x, re = |y| / (2 im)
715 im = std::sqrt(half * (modulus - x));
716 if (scale == 1 && std::abs(y) < R {1}) {
717 re = std::abs(y / im);
718 im = std::ldexp(im, scale);
719 scale = 0;
720 }
721 else {
722 re = std::abs(half * (y / im));
723 }
724 }
725 if (scale != 0) {
726 re = std::ldexp(re, scale);
727 im = std::ldexp(im, scale);
728 }
729 return {re, std::copysign(im, y)};
730 }
731
738 template <std::floating_point R>
739 [[nodiscard]] std::complex<R> complex_atanh(const std::complex<R>& z)
740 {
741 const R x {z.real()};
742 const R y {z.imag()};
743 const R half_pi {std::numbers::pi_v<R> / R {2}};
744 const R eps {std::numeric_limits<R>::epsilon()};
745 const bool x_finite {std::isfinite(x)};
746 const bool y_finite {std::isfinite(y)};
747 if (!x_finite || !y_finite) {
748 if (std::isinf(y)) {
749 return {std::copysign(R {0}, x), std::copysign(half_pi, y)};
750 }
751 if (std::isinf(x) || x == R {0}) { // y NaN where x is 0
752 return {std::copysign(R {0}, x), y_finite ? std::copysign(half_pi, y) : std::numeric_limits<R>::quiet_NaN()};
753 }
754 return {std::numeric_limits<R>::quiet_NaN(), std::numeric_limits<R>::quiet_NaN()};
755 }
756 if (x == R {0} && y == R {0}) {
757 return z;
758 }
759 if (std::abs(x) >= R {16} / eps || std::abs(y) >= R {16} / eps) {
760 R re {};
761 if (std::abs(y) <= R {1}) {
762 re = R {1} / x;
763 }
764 else if (std::abs(x) <= R {1}) {
765 re = x / y / y;
766 }
767 else {
768 const R h {std::hypot(x / R {2}, y / R {2})};
769 re = x / h / h / R {4};
770 }
771 return {re, std::copysign(half_pi, y)};
772 }
773 R re {};
774 if (std::abs(x) == R {1} && std::abs(y) < eps * eps) {
775 re = std::copysign(R {0.5}, x) * (std::numbers::ln2_v<R> - std::log(std::abs(y)));
776 }
777 else {
778 const R i2 {std::abs(y) >= eps * eps ? y * y : R {0}};
779 const R plus {R {1} + x};
780 const R minus {R {1} - x};
781 const R num {libm_add_product(i2, plus, plus)};
782 const R den {libm_add_product(i2, minus, minus)};
783 const R f {num / den};
784 if (f < R {0.5}) {
785 re = R {0.25} *std::log(f);
786 }
787 else {
788 const R four_x {R {4} *x};
789 re = R {0.25} *std::log1p(four_x / den);
790 }
791 }
792 const R absx {std::max(std::abs(x), std::abs(y))};
793 const R absy {std::min(std::abs(x), std::abs(y))};
794 R den {};
795 if (absy < eps / R {2}) {
796 const R product {(R {1} - absx) * (R {1} + absx)};
797 den = product == R {0} ? R {0} : product; // +0 for −0, as glibc's
798 }
799 else if (absx >= R {1} || (absx < R {0.75} && absy < R {0.5})) {
800 den = libm_sum_of_products(R {1} - absx, R {1} + absx, -absy, absy);
801 }
802 else {
804 }
805 const R twice_y {R {2} *y};
806 return {re, R {0.5} *std::atan2(twice_y, den)};
807 }
808
817 template <std::floating_point R>
818 [[nodiscard]] std::complex<R> kernel_asinh(const std::complex<R>& z,
819 bool adjust)
820 {
821 const R eps {std::numeric_limits<R>::epsilon()};
822 const R rx {std::abs(z.real())};
823 const R ix {std::abs(z.imag())};
824 const R sign {z.imag()};
825 R re {};
826 R im {};
827 // the imaginary part from (a, b) as atan2(b, a), or atan2(a, ±b) where adjusted
828 const auto angle {[&](R a, R b) { return adjust ? std::atan2(a, std::copysign(b, sign)) : std::atan2(b, a); }};
829 const auto through_log {[&](std::complex<R> y) {
830 if (adjust) {
831 y = {std::copysign(y.imag(), sign), y.real()};
832 }
833 return complex_log(y);
834 }};
835 if (rx >= R {1} / eps || ix >= R {1} / eps) { // z + √(1 + z²) as 2z, without the square's overflow
836 const std::complex<R> res {through_log({rx, ix})};
837 re = res.real() + std::numbers::ln2_v<R>;
838 im = res.imag();
839 }
840 else if (rx >= R {0.5} && ix < eps / R {8}) {
841 const R s {std::hypot(R {1}, rx)};
842 re = std::log(rx + s);
843 im = adjust ? std::atan2(s, z.imag()) : std::atan2(ix, s);
844 }
845 else if (rx < eps / R {8} && ix >= R {1.5}) {
846 const R s {std::sqrt((ix + R {1}) * (ix - R {1}))};
847 re = std::log(ix + s);
848 im = angle(rx, s);
849 }
850 else if (ix > R {1} && ix < R {1.5} && rx < R {0.5}) {
851 const R ix2m1 {(ix + R {1}) * (ix - R {1})};
852 if (rx < eps * eps) {
853 const R s {std::sqrt(ix2m1)};
854 re = std::log1p(R {2} *libm_add_product(ix2m1, ix, s)) / R {2};
855 im = angle(rx, s);
856 }
857 else {
858 const R rx2 {rx * rx};
859 const R f {rx2 * libm_add_product(R {2} + rx2, R {2} *ix, ix)};
860 const R d {std::sqrt(libm_add_product(f, ix2m1, ix2m1))};
861 const R dp {d + ix2m1};
862 const R dm {f / dp};
863 const R r1 {std::sqrt((dm + rx2) / R {2})};
864 const R r2 {rx * ix / r1};
865 re = std::log1p(rx2 + dp + (R {2} *libm_sum_of_products(rx, r1, ix, r2))) / R {2};
866 im = angle(rx + r1, ix + r2);
867 }
868 }
869 else if (ix == R {1} && rx < R {0.5}) {
870 if (rx < eps / R {8}) {
871 const R root {std::sqrt(rx)};
872 re = std::log1p(R {2} *(rx + root)) / R {2};
873 im = angle(root, R {1});
874 }
875 else {
876 const R d {rx * std::sqrt(libm_add_product(R {4}, rx, rx))};
877 const R s1 {std::sqrt(libm_add_product(d, rx, rx) / R {2})};
878 const R s2 {std::sqrt(libm_add_product(d, -rx, rx) / R {2})};
879 re = std::log1p(libm_add_product(d, rx, rx) + (R {2} *libm_add_product(s2, rx, s1))) / R {2};
880 im = angle(rx + s1, R {1} + s2);
881 }
882 }
883 else if (ix < R {1} && rx < R {0.5}) {
884 if (ix < eps) {
885 const R s {std::hypot(R {1}, rx)};
886 re = std::log1p(R {2} *rx * (rx + s)) / R {2};
887 im = adjust ? std::atan2(s, z.imag()) : std::atan2(ix, s);
888 }
889 else if (rx < eps * eps) {
890 const R onemix2 {(R {1} + ix) * (R {1} - ix)};
891 const R s {std::sqrt(onemix2)};
892 re = std::log1p(R {2} *rx / s) / R {2};
893 im = adjust ? std::atan2(s, z.imag()) : std::atan2(ix, s);
894 }
895 else {
896 const R onemix2 {(R {1} + ix) * (R {1} - ix)};
897 const R rx2 {rx * rx};
898 const R f {rx2 * libm_add_product(R {2} + rx2, R {2} *ix, ix)};
899 const R d {std::sqrt(libm_add_product(f, onemix2, onemix2))};
900 const R dp {d + onemix2};
901 const R dm {f / dp};
902 const R r1 {std::sqrt((dp + rx2) / R {2})};
903 const R r2 {rx * ix / r1};
904 re = std::log1p(rx2 + dm + (R {2} *libm_sum_of_products(rx, r1, ix, r2))) / R {2};
905 im = angle(rx + r1, ix + r2);
906 }
907 }
908 else { // z + √(1 + z²), of 1 + z² = (rx − ix)(rx + ix) + 1 + 2 rx ix i
909 const std::complex<R> root {complex_sqrt(std::complex<R> {libm_add_product(R {1}, rx - ix, rx + ix), R {2} *rx * ix})};
910 const std::complex<R> res {through_log({root.real() + rx, root.imag() + ix})};
911 re = res.real();
912 im = res.imag();
913 }
914 return {std::copysign(re, z.real()), std::copysign(im, adjust ? R {1} : z.imag())};
915 }
916
921 template <std::floating_point R>
922 [[nodiscard]] std::complex<R> complex_asinh(const std::complex<R>& z)
923 {
924 const R x {z.real()};
925 const R y {z.imag()};
926 const R nan {std::numeric_limits<R>::quiet_NaN()};
927 if (!std::isfinite(x) || !std::isfinite(y)) {
928 if (std::isinf(y)) {
929 const R quarter {x == R {0} || std::isfinite(x) ? std::numbers::pi_v<R> / R {2} : std::numbers::pi_v<R> / R {4}};
930 return {std::copysign(std::numeric_limits<R>::infinity(), x), std::isnan(x) ? nan : std::copysign(quarter, y)};
931 }
932 if (!std::isfinite(x)) { // y finite or NaN
933 return {x, ((std::isinf(x) && std::isfinite(y)) || y == R {0}) ? std::copysign(R {0}, y) : nan};
934 }
935 return {nan, nan}; // x finite, y NaN
936 }
937 if (x == R {0} && y == R {0}) {
938 return z;
939 }
940 return kernel_asinh(z, false);
941 }
942
944 template <std::floating_point R>
945 [[nodiscard]] std::complex<R> complex_asin(const std::complex<R>& z)
946 {
947 const R nan {std::numeric_limits<R>::quiet_NaN()};
948 if (std::isnan(z.real()) || std::isnan(z.imag())) {
949 if (z.real() == R {0}) {
950 return z;
951 }
952 if (std::isinf(z.real()) || std::isinf(z.imag())) {
953 return {nan, std::copysign(std::numeric_limits<R>::infinity(), z.imag())};
954 }
955 return {nan, nan};
956 }
957 const std::complex<R> y {complex_asinh(std::complex<R> {-z.imag(), z.real()})};
958 return {y.imag(), -y.real()};
959 }
960
963 template <std::floating_point R>
964 [[nodiscard]] std::complex<R> complex_acos(const std::complex<R>& z)
965 {
966 if (!std::isfinite(z.real()) || !std::isfinite(z.imag()) || (z.real() == R {0} && z.imag() == R {0})) {
967 const std::complex<R> y {complex_asin(z)};
968 const R re {(std::numbers::pi_v<R> / R {2}) - y.real()};
969 return {re == R {0} ? R {0} : re, -y.imag()}; // +0 for −0, as glibc's
970 }
971 const std::complex<R> y {kernel_asinh(std::complex<R> {-z.imag(), z.real()}, true)};
972 return {y.imag(), y.real()};
973 }
974
977 template <std::floating_point R>
978 [[nodiscard]] std::complex<R> complex_acosh(const std::complex<R>& z)
979 {
980 const R x {z.real()};
981 const R y {z.imag()};
982 const R nan {std::numeric_limits<R>::quiet_NaN()};
983 const R inf {std::numeric_limits<R>::infinity()};
984 const R half_pi {std::numbers::pi_v<R> / R {2}};
985 const R quarter {std::numbers::pi_v<R> / R {4}};
986 if (!std::isfinite(x) || !std::isfinite(y)) {
987 if (std::isinf(y)) {
988 const R angle {std::isinf(x) ? (x < R {0} ? std::numbers::pi_v<R> - quarter : quarter) : half_pi};
989 return {inf, std::isnan(x) ? nan : std::copysign(angle, y)};
990 }
991 if (std::isinf(x)) {
992 return {inf, std::isnan(y) ? nan : std::copysign(std::signbit(x) ? std::numbers::pi_v<R> : R {0}, y)};
993 }
994 return {nan, x == R {0} ? half_pi : nan}; // a NaN part, the other finite
995 }
996 if (x == R {0} && y == R {0}) {
997 return {R {0}, std::copysign(half_pi, y)};
998 }
999 const std::complex<R> w {kernel_asinh(std::complex<R> {-y, x}, true)};
1000 return std::signbit(y) ? std::complex<R> {w.real(), -w.imag()} : std::complex<R> {-w.real(), w.imag()};
1001 }
1002
1009 template <std::floating_point R>
1010 [[nodiscard]] std::complex<R> complex_atan(const std::complex<R>& z)
1011 {
1012 const R x {z.real()};
1013 const R y {z.imag()};
1014 const R half_pi {std::numbers::pi_v<R> / R {2}};
1015 const R eps {std::numeric_limits<R>::epsilon()};
1016 const R nan {std::numeric_limits<R>::quiet_NaN()};
1017 if (!std::isfinite(x) || !std::isfinite(y)) {
1018 if (std::isinf(x)) {
1019 return {std::copysign(half_pi, x), std::copysign(R {0}, y)};
1020 }
1021 if (std::isinf(y)) {
1022 return {std::isnan(x) ? nan : std::copysign(half_pi, x), std::copysign(R {0}, y)};
1023 }
1024 return {nan, y == R {0} ? std::copysign(R {0}, y) : nan}; // a NaN part, the other finite
1025 }
1026 if (x == R {0} && y == R {0}) {
1027 return z;
1028 }
1029 if (std::abs(x) >= R {16} / eps || std::abs(y) >= R {16} / eps) {
1030 R im {};
1031 if (std::abs(x) <= R {1}) {
1032 im = R {1} / y;
1033 }
1034 else if (std::abs(y) <= R {1}) {
1035 im = y / x / x;
1036 }
1037 else {
1038 const R h {std::hypot(x / R {2}, y / R {2})};
1039 im = y / h / h / R {4};
1040 }
1041 return {std::copysign(half_pi, x), im};
1042 }
1043 const R absx {std::max(std::abs(x), std::abs(y))};
1044 const R absy {std::min(std::abs(x), std::abs(y))};
1045 R den {};
1046 if (absy < eps / R {2}) {
1047 const R product {(R {1} - absx) * (R {1} + absx)};
1048 den = product == R {0} ? R {0} : product; // +0 for −0, as glibc's
1049 }
1050 else if (absx >= R {1} || (absx < R {0.75} && absy < R {0.5})) {
1051 den = libm_sum_of_products(R {1} - absx, R {1} + absx, -absy, absy);
1052 }
1053 else {
1055 }
1056 const R twice_x {R {2} *x};
1057 const R re {R {0.5} *std::atan2(twice_x, den)};
1058 R im {};
1059 if (std::abs(y) == R {1} && std::abs(x) < eps * eps) {
1060 im = std::copysign(R {0.5}, y) * (std::numbers::ln2_v<R> - std::log(std::abs(x)));
1061 }
1062 else {
1063 const R r2 {std::abs(x) >= eps * eps ? x * x : R {0}};
1064 const R plus {y + R {1}};
1065 const R minus {y - R {1}};
1066 const R num {libm_add_product(r2, plus, plus)};
1067 const R below {libm_add_product(r2, minus, minus)};
1068 const R f {num / below};
1069 if (f < R {0.5}) {
1070 im = R {0.25} *std::log(f);
1071 }
1072 else {
1073 const R four_y {R {4} *y};
1074 im = R {0.25} *std::log1p(four_y / below);
1075 }
1076 }
1077 return {re, im};
1078 }
1079
1081 template <std::floating_point R>
1082 [[nodiscard]] std::complex<R> complex_log2(const std::complex<R>& z)
1083 {
1084 const std::complex<R> w {complex_log(z)};
1085 return {w.real() * std::numbers::log2e_v<R>, w.imag() * std::numbers::log2e_v<R>};
1086 }
1087
1089 template <std::floating_point R>
1090 [[nodiscard]] std::complex<R> complex_log10(const std::complex<R>& z)
1091 {
1092 const std::complex<R> w {complex_log(z)};
1093 return {w.real() * std::numbers::log10e_v<R>, w.imag() * std::numbers::log10e_v<R>};
1094 }
1095
1097 template <std::floating_point R>
1098 [[nodiscard]] std::complex<R> complex_exp2(const std::complex<R>& z)
1099 {
1100 return complex_exp(std::complex<R> {z.real() * std::numbers::ln2_v<R>, z.imag() * std::numbers::ln2_v<R>});
1101 }
1102
1109 template <std::floating_point R>
1110 [[nodiscard]] std::complex<R> complex_expm1(const std::complex<R>& z)
1111 {
1112 if (z.real() > exp_bound<R> && std::isfinite(z.imag())) {
1113 const std::complex<R> w {complex_exp(z)};
1114 return {w.real() - R {1}, w.imag()};
1115 }
1116 const R a {std::sin(z.imag() / R {2})};
1117 const R real {std::expm1(z.real()) * separate_cosine(z.imag())};
1118 const R half {R {2} *a * a};
1119 return {real - half, std::exp(z.real()) * separate_sine(z.imag())};
1120 }
1121
1130 template <std::floating_point R>
1131 [[nodiscard]] std::complex<R> complex_log1p(const std::complex<R>& z)
1132 {
1133 const R x {z.real()};
1134 const R y {z.imag()};
1135 if (x == R {0} && y == R {0}) {
1136 return z;
1137 }
1138 R d {-R {1}};
1139 if (std::abs(x) <= R {3} && std::abs(y) <= R {3}) {
1140 const R xx {x * x};
1141 const R xx_err {std::fma(x, x, -xx)};
1142 const R yy {y * y};
1143 const R yy_err {std::fma(y, y, -yy)};
1144 const R twice {R {2} *x};
1145 const R first {twice + yy}; // two-sums: each rounding error kept
1146 const R bv {first - twice};
1147 const R first_e {(twice - (first - bv)) + (yy - bv)};
1148 const R sum {first + xx};
1149 const R cv {sum - first};
1150 const R sum_e {(first - (sum - cv)) + (xx - cv)};
1151 d = sum + (((first_e + sum_e) + xx_err) + yy_err);
1152 }
1153 if (d >= R {-0.5}) {
1154 return {std::log1p(d) / R {2}, std::atan2(y, x + R {1})};
1155 }
1156 return complex_log(std::complex<R> {x + R {1}, y});
1157 }
1158
1163 template <std::floating_point R>
1164 [[nodiscard]] std::complex<R> complex_sign(const std::complex<R>& z)
1165 {
1166 const R x {z.real()};
1167 const R y {z.imag()};
1168 const R nan {std::numeric_limits<R>::quiet_NaN()};
1169 const R magnitude {std::hypot(x, y)};
1170 if (std::isnan(magnitude)) {
1171 return {nan, nan};
1172 }
1173 if (std::isinf(magnitude)) {
1174 if (std::isinf(x)) {
1175 return std::isinf(y) ? std::complex<R> {nan, nan} : std::complex<R> {x > R {0} ? R {1} : R {-1}, R {0}};
1176 }
1177 return {R {0}, y > R {0} ? R {1} : R {-1}};
1178 }
1179 if (magnitude == R {0}) {
1180 return {R {0}, R {0}};
1181 }
1182 return {x / magnitude, y / magnitude};
1183 }
1184} // namespace numerical::detail
1185
1186#endif // NUMERICAL_COMPLEX_MATH_HPP
#define NUMERICAL_OUT_OF_LINE
Definition buffer.hpp:30
What every exception NumericAL throws is, beside its standard base (all but std::bad_alloc and std::s...
Definition vector.hpp:40
std::complex< R > complex_asinh(const std::complex< R > &z)
asinh(z), as glibc's casinh: C's Annex G for the infinities and NaNs, z itself at ±0 ± 0i,...
std::complex< R > complex_sign(const std::complex< R > &z)
z / |z|, as NumPy 2's sign of a complex number and the array API's: 0 for 0, NaN for a NaN modulus,...
constexpr R half_exp_bound
Half of it, past which tanh's parts are ±1 and a quotient by exp(2x): 354 for double,...
R separate_sine(R x)
std::sin of x in a call of its own, as NumPy's formulas take it: no build fuses it with a cos of the ...
R libm_add_product(R s, R a, R b)
s + a·b as the C library's build computes s += a·b: fused where it fuses, as libm_sum_of_products.
std::complex< R > complex_log(const std::complex< R > &z)
log(z): log|z| + i arg(z), log|z| as log1p(|z|² − 1) / 2 near the unit circle (|z|² − 1 exact or almo...
R libm_sum_of_products(R a, R b, R c, R d)
a·b + c·d as the C library's build computes it: fma(a, b, c·d) where it fuses (libm_fuses),...
std::complex< R > complex_sinh(const std::complex< R > &z)
sinh(z): sinh(re) cos(im) + i cosh(re) sin(im) of |re|, the sign of re carried by the cosine; past ex...
constexpr R exp_bound
The real part past which exp of it overflows, rounded down: 709 for double, 88 for float.
std::complex< R > complex_sin(const std::complex< R > &z)
sin(z): sin(re) cosh(im) + i cos(re) sinh(im) of |re|, the sign of re carried by the sine; an imagina...
T square(const T &x)
x · x, by the type's own product (a complex one's C Annex G, as the library's *).
std::complex< R > complex_tan(const std::complex< R > &z)
tan(z): (sin(re) cos(re) + i sinh(im) cosh(im)) / (cos(re)² + sinh(im)²); past half_exp_bound the ima...
std::complex< R > complex_exp2(const std::complex< R > &z)
2^z, as NumPy's: complex_exp of z times ln 2, each part.
std::complex< R > complex_log2(const std::complex< R > &z)
log2(z), as NumPy's: complex_log times log₂ e, each part.
std::complex< R > complex_log1p(const std::complex< R > &z)
log(1 + z): the imaginary part atan2(im, 1 + re), as NumPy's; the real part log|1 + z|,...
std::complex< R > complex_asin(const std::complex< R > &z)
asin(z), as glibc's casin: −i asinh(iz); a NaN part as Annex G has it.
double unit_circle_offset(double x, double y)
x² + y² − 1 for 0.5 ≤ x < 1, y ≤ x and x² + y² ≥ 0.5, almost exactly: each square split into its roun...
R separate_cosine(R x)
std::cos of x in a call of its own, as separate_sine.
std::complex< R > complex_acos(const std::complex< R > &z)
acos(z), as glibc's cacos: π/2 − asin(z) for the infinities, NaNs and zeros, else kernel_asinh of iz ...
std::complex< R > complex_expm1(const std::complex< R > &z)
exp(z) − 1, as NumPy's: expm1(re) cos(im) − 2 sin²(im/2) + i exp(re) sin(im), the sine and the cosine...
std::complex< R > complex_tanh(const std::complex< R > &z)
tanh(z): (sinh(re) cosh(re) + i sin(im) cos(im)) / (sinh(re)² + cos(im)²); past half_exp_bound the re...
std::complex< R > complex_cosh(const std::complex< R > &z)
cosh(z): cosh(re) cos(im) + i sinh(re) sin(im); past exp_bound, exp(|re|) / 2 times the cosine and th...
void small_sincos(R x, R &sine, R &cosine)
sin and cos of x (sine_and_cosine), or x and 1 for one under the smallest normal value (an exact sine...
std::complex< R > complex_exp(const std::complex< R > &z)
exp(z): exp(re) times cos(im) + i sin(im), a real part past exp_bound taken off in steps of it (each ...
bool unit_circle_squares_reach_half(R x, R y)
Whether x² + y² ≥ 0.5, as glibc's build computes the sum (libm_sum_of_products).
std::complex< R > complex_atanh(const std::complex< R > &z)
atanh(z), as glibc's catanh: C's Annex G for the infinities and NaNs; π/2 and the reciprocal past 16/...
void sine_and_cosine(double x, double &sine, double &cosine)
sin and cos of x together, as glibc's complex functions take them: its sincos under glibc (whose sing...
std::complex< R > complex_sqrt(const std::complex< R > &z)
The square root of a complex number, as the GNU C library's csqrt computes it (NumPy's on Linux,...
std::complex< R > kernel_asinh(const std::complex< R > &z, bool adjust)
asinh(z) of a finite nonzero z, as glibc's __kernel_casinh, its imaginary part taken from π/2 where a...
T root(const T &x)
The square root of a scalar, as std::sqrt gives it.
std::complex< R > complex_acosh(const std::complex< R > &z)
acosh(z), as glibc's cacosh: Annex G for the infinities, NaNs and zeros, else kernel_asinh of iz adju...
std::complex< R > complex_log10(const std::complex< R > &z)
log10(z), as NumPy's: complex_log times log₁₀ e, each part.
bool libm_fuses() noexcept
Whether the C library's complex functions fuse their sums of products, a·b + c·d as fma(a,...
std::complex< R > complex_cos(const std::complex< R > &z)
cos(z), as cosh(i z): complex_cosh of −im + i re.
std::complex< R > complex_atan(const std::complex< R > &z)
atan(z), as glibc's catan: C's Annex G for the infinities and NaNs; π/2 and the reciprocal past 16/ε;...
@ fused
std::fma, where every target has the instruction.
T sum(const tensor< T > &t)
The sum of every element, by pairwise halving (0 for an empty tensor), on the threads where they are ...