1#[derive(Clone, Copy, Default, PartialEq, PartialOrd, Debug)]
13#[repr(C)]
14pub struct Complex<F> {
15 pub re: F,
17 pub im: F,
19}
20
21#[allow(non_camel_case_types)] pub type c64 = Complex<f32>;
24
25#[allow(non_camel_case_types)] pub type c128 = Complex<f64>;
28
29impl<F> Complex<F> {
30 pub const fn new(re: F, im: F) -> Self {
32 Self { re, im }
33 }
34}
35
36use std::ops::{Add, Div, Neg};
37
38macro_rules! impl_complex {
39 ($f:ident, $k:expr, $e_hi:expr) => {
40 impl std::ops::Add for Complex<$f> {
41 type Output = Self;
42 #[inline]
44 fn add(self, o: Self) -> Self {
45 Self::new(self.re + o.re, self.im + o.im)
46 }
47 }
48
49 impl std::ops::Sub for Complex<$f> {
50 type Output = Self;
51 #[inline]
53 fn sub(self, o: Self) -> Self {
54 Self::new(self.re - o.re, self.im - o.im)
55 }
56 }
57
58 impl std::ops::Mul for Complex<$f> {
59 type Output = Self;
60 #[inline]
63 fn mul(self, o: Self) -> Self {
64 Self::new(
65 self.re.mul_add(o.re, -(self.im * o.im)),
66 self.im.mul_add(o.re, self.re * o.im),
67 )
68 }
69 }
70
71 impl std::ops::Neg for Complex<$f> {
72 type Output = Self;
73 #[inline]
75 fn neg(self) -> Self {
76 Self::new(-self.re, -self.im)
77 }
78 }
79
80 impl std::ops::Div for Complex<$f> {
81 type Output = Self;
82 #[inline]
84 fn div(self, o: Self) -> Self {
85 self.div_xla(o)
86 }
87 }
88
89 impl Complex<$f> {
90 #[inline]
92 pub fn conj(self) -> Self {
93 Self::new(self.re, -self.im)
94 }
95
96 pub fn div_xla(self, o: Self) -> Self {
99 let (a_r, a_i, b_r, b_i) = (self.re, self.im, o.re, o.im);
100 let (b_r_abs, b_i_abs) = (b_r.abs(), b_i.abs());
101 let (result_r, result_i) = if b_r_abs < b_i_abs {
102 let ratio = b_r / b_i;
103 let denom = b_i + ratio * b_r;
104 ((ratio * a_r + a_i) / denom, (ratio * a_i - a_r) / denom)
105 } else {
106 let ratio = b_i / b_r;
107 let denom = b_r + ratio * b_i;
108 ((ratio * a_i + a_r) / denom, (a_i - ratio * a_r) / denom)
109 };
110 if !(result_r.is_nan() && result_i.is_nan()) {
111 return Self::new(result_r, result_i);
112 }
113 let inf = $f::INFINITY;
114 let (a_r_abs, a_i_abs) = (a_r.abs(), a_i.abs());
115 if b_r_abs == 0.0 && b_i_abs == 0.0 && (!a_r.is_nan() || !a_i.is_nan()) {
116 let s = inf.copysign(b_r);
118 return Self::new(s * a_r, s * a_i);
119 }
120 let one_or_zero = |inf_: bool, sign: $f| {
121 $f::copysign(if inf_ { 1.0 } else { 0.0 }, sign)
122 };
123 if (a_r_abs == inf || a_i_abs == inf) && b_r_abs != inf && b_i_abs != inf {
124 let x = one_or_zero(a_r_abs == inf, a_r);
126 let y = one_or_zero(a_i_abs == inf, a_i);
127 return Self::new(inf * (x * b_r + y * b_i), inf * (y * b_r - x * b_i));
128 }
129 if (b_r_abs == inf || b_i_abs == inf) && a_r_abs != inf && a_i_abs != inf {
130 let x = one_or_zero(b_r_abs == inf, b_r);
132 let y = one_or_zero(b_i_abs == inf, b_i);
133 return Self::new(0.0 * (a_r * x + a_i * y), 0.0 * (a_i * x - a_r * y));
134 }
135 Self::new(result_r, result_i)
136 }
137
138 pub fn abs(self) -> $f {
142 let (x1, x2) = (self.re, self.im);
143 let (a1, a2) = (x1.abs(), x2.abs());
144 let m = max_nan(a1, a2);
145 let k: i32 = $k;
147 let e_hi: i32 = $e_hi;
148 let hi = m >= (2.0 as $f).powi(e_hi);
149 let lo = m <= (2.0 as $f).powi(e_hi - k);
150 let (s_down, s_up) = ((2.0 as $f).powi(-k), (2.0 as $f).powi(k));
151 let scale = |x: $f| {
152 if hi {
153 x * s_down
154 } else if lo {
155 x * s_up
156 } else {
157 x
158 }
159 };
160 let (y1, y2) = (scale(x1), scale(x2));
161 let inv_scale = if hi {
162 s_up
163 } else if lo {
164 s_down
165 } else {
166 1.0
167 };
168 let r = (y1 * y1 + y2 * y2).sqrt() * inv_scale;
169 if a1 == $f::INFINITY || a2 == $f::INFINITY {
170 $f::INFINITY
171 } else {
172 r
173 }
174 }
175
176 fn xla_abs(self) -> $f {
180 let (min, max) = self.min_max_parts();
181 let div = min / max;
182 let r = max * (1.0 + div * div).sqrt();
183 if r.is_nan() { min } else { r }
184 }
185
186 #[inline]
190 fn min_max_parts(self) -> ($f, $f) {
191 let (x, y) = (self.re.abs(), self.im.abs());
192 let max = if y > x { y } else { x };
193 let min = if y < x { y } else { x };
194 (min, max)
195 }
196
197 fn log_abs(self) -> $f {
200 let (min, max) = self.min_max_parts();
201 if max == 0.0 {
202 return $f::NEG_INFINITY;
203 }
204 if max == $f::INFINITY {
205 return max;
206 }
207 if self.re.is_nan() || self.im.is_nan() {
208 return $f::NAN;
209 }
210 let div = min / max;
211 max.ln() + 0.5 * (div * div).ln_1p()
212 }
213
214 #[inline]
216 pub fn arg(self) -> $f {
217 self.im.atan2(self.re)
218 }
219
220 pub fn sign(self) -> Self {
222 if self.re.is_nan() || self.im.is_nan() {
223 return Self::new($f::NAN, $f::NAN);
224 }
225 let abs = self.xla_abs();
226 if abs == 0.0 {
227 self
228 } else {
229 Self::new(self.re / abs, self.im / abs)
230 }
231 }
232
233 pub fn exp(self) -> Self {
236 let (a, b) = (self.re, self.im);
237 let e = a.exp();
238 let im = if b == 0.0 { b } else { e * b.sin() };
239 Self::new(e * b.cos(), im)
240 }
241
242 pub fn expm1(self) -> Self {
244 let (a, b) = (self.re, self.im);
246 let h = (b * 0.5).sin();
247 let im = if b == 0.0 { b } else { a.exp() * b.sin() };
248 Self::new(a.exp_m1() * b.cos() - 2.0 * h * h, im)
249 }
250
251 pub fn log(self) -> Self {
253 Self::new(self.log_abs(), self.arg())
254 }
255
256 pub fn log1p(self) -> Self {
258 let (a, b) = (self.re, self.im);
259 let re = if a.abs() < 0.5 && b.abs() < 0.5 {
261 0.5 * (a * a + b * b + 2.0 * a).ln_1p()
262 } else {
263 Self::new(a + 1.0, b).log_abs()
264 };
265 Self::new(re, b.atan2(a + 1.0))
266 }
267
268 pub fn sqrt(self) -> Self {
270 let (a, b) = (self.re, self.im);
271 if a == 0.0 && b == 0.0 {
272 return Self::new(0.0, b);
273 }
274 if b.is_infinite() {
275 return Self::new($f::INFINITY, b);
276 }
277 if a == $f::NEG_INFINITY {
278 return if b.is_nan() {
279 Self::new(b, $f::INFINITY)
280 } else {
281 Self::new(0.0, $f::INFINITY.copysign(b))
282 };
283 }
284 if a == $f::INFINITY {
285 return if b.is_nan() {
286 Self::new(b, b)
287 } else {
288 Self::new(a, (0.0 as $f).copysign(b))
289 };
290 }
291 let t = if a.abs().max(b.abs()) > $f::MAX / 8.0 {
294 let r = Self::new(a * 0.25, b * 0.25).abs();
295 (a.abs() * 0.25 + r).sqrt() * std::f64::consts::SQRT_2 as $f
296 } else {
297 ((a.abs() + self.abs()) * 0.5).sqrt()
298 };
299 if a >= 0.0 {
300 Self::new(t, b / (2.0 * t))
301 } else {
302 Self::new(b.abs() / (2.0 * t), t.copysign(b))
303 }
304 }
305
306 pub fn rsqrt(self) -> Self {
308 if self.re.is_infinite() || self.im.is_infinite() {
309 return Self::new(0.0, -0.0);
310 }
311 Self::new(1.0, 0.0).div(self.sqrt())
312 }
313
314 pub fn sin(self) -> Self {
316 let (a, b) = (self.re, self.im);
317 let (e1m, e2m) = (b.exp_m1(), (-b).exp_m1());
318 let snh = (e1m - e2m) / 2.0;
319 let csh = (e1m + e2m + 2.0) / 2.0;
320 let im = a.cos() * snh;
321 if a == 0.0 {
322 Self::new(0.0, im)
323 } else {
324 Self::new(a.sin() * csh, im)
325 }
326 }
327
328 pub fn cos(self) -> Self {
330 let (a, b) = (self.re, self.im);
331 let (e1m, e2m) = (b.exp_m1(), (-b).exp_m1());
332 let snh = (e1m - e2m) / 2.0;
333 let csh = (e1m + e2m + 2.0) / 2.0;
334 let re = a.cos() * csh;
335 if a == 0.0 {
336 Self::new(re, 0.0)
337 } else {
338 Self::new(re, -a.sin() * snh)
339 }
340 }
341
342 pub fn tan(self) -> Self {
344 let t = Self::new(-self.im, self.re).tanh();
345 Self::new(t.im, -t.re)
346 }
347
348 pub fn tanh(self) -> Self {
350 let (a, b) = (self.re, self.im);
351 if b == 0.0 {
352 return Self::new(a.tanh(), b);
353 }
354 if a.abs() > $f::MANTISSA_DIGITS as $f * 0.5 {
357 let e = (-2.0 * a.abs()).exp();
358 let im = 4.0 * b.sin() * b.cos() * e;
359 let im = if im.is_nan() && !b.is_nan() { 0.0 } else { im };
360 let im = if b.is_nan() { 0.0 } else { im };
361 return Self::new((1.0 as $f).copysign(a), im);
362 }
363 let (th, t) = (a.tanh(), b.tan());
366 let denom = 1.0 + th * th * t * t;
367 Self::new(th * (1.0 + t * t) / denom, t * (1.0 - th * th) / denom)
368 }
369
370 pub fn logistic(self) -> Self {
372 let one = Self::new(1.0, 0.0);
373 one.div(one.add(self.neg().exp()))
374 }
375
376 pub fn pow(self, y: Self) -> Self {
381 let (a, b, c, d) = (self.re, self.im, y.re, y.im);
382 if (c == 0.0 && d == 0.0) || (a == 1.0 && b == 0.0) {
383 return Self::new(1.0, 0.0);
384 }
385 if d == 0.0 && b == 0.0 && a > 0.0 && !c.is_nan() {
386 return Self::new(a.powf(c), 0.0);
387 }
388 if a == 0.0 && (b == 0.0 || b.is_nan()) && d == 0.0 && c > 0.0 {
389 return Self::new(0.0, 0.0);
390 }
391 let (lr, arg) = (self.xla_abs().ln(), b.atan2(a));
393 let coeff = (c * lr).exp() * (-d * arg).exp();
394 let q = c * arg + d * lr;
395 Self::new(coeff * q.cos(), coeff * q.sin())
396 }
397
398 #[inline]
401 pub fn max(self, o: Self) -> Self {
402 let gt = if self.re == o.re {
403 self.im > o.im
404 } else {
405 self.re > o.re
406 };
407 if gt { self } else { o }
408 }
409
410 #[inline]
413 pub fn min(self, o: Self) -> Self {
414 let lt = if self.re == o.re {
415 self.im < o.im
416 } else {
417 self.re < o.re
418 };
419 if lt { self } else { o }
420 }
421
422 #[inline]
424 pub fn is_finite(self) -> bool {
425 self.re.is_finite() && self.im.is_finite()
426 }
427 }
428 };
429}
430
431fn max_nan<F: num_like::Float>(a: F, b: F) -> F {
433 if a.is_nan_() || b.is_nan_() {
434 F::NAN_
435 } else if a > b {
436 a
437 } else {
438 b
439 }
440}
441
442mod num_like {
443 pub(super) trait Float: Copy + PartialOrd {
445 const NAN_: Self;
446 fn is_nan_(self) -> bool;
447 }
448 impl Float for f32 {
449 const NAN_: Self = f32::NAN;
450 fn is_nan_(self) -> bool {
451 self.is_nan()
452 }
453 }
454 impl Float for f64 {
455 const NAN_: Self = f64::NAN;
456 fn is_nan_(self) -> bool {
457 self.is_nan()
458 }
459 }
460}
461
462impl_complex!(f32, 75, 63);
464impl_complex!(f64, 537, 511);
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469 use std::ops::{Mul, Sub};
470
471 fn close(a: c128, b: c128) -> bool {
472 (a.re - b.re).abs() <= 1e-12 * (1.0 + b.re.abs())
473 && (a.im - b.im).abs() <= 1e-12 * (1.0 + b.im.abs())
474 }
475
476 #[test]
477 fn arithmetic() {
478 let x = c128::new(1.0, 2.0);
479 let y = c128::new(3.0, -1.0);
480 assert_eq!(x.mul(y), c128::new(5.0, 5.0));
481 assert!(close(x.div(y).mul(y), x));
482 assert_eq!(c128::new(3.0, 4.0).abs(), 5.0);
483 assert_eq!(c64::new(3e30, 4e30).abs(), 5e30);
484 assert_eq!(c64::new(3e-30, 4e-30).abs(), 5e-30);
485 assert_eq!(c128::new(f64::INFINITY, f64::NAN).abs(), f64::INFINITY);
486 let q = c128::new(1.0, 1.0).div(c128::new(0.0, 0.0));
488 assert_eq!((q.re, q.im), (f64::INFINITY, f64::INFINITY));
489 let q = c128::new(1.0, 1.0).div(c128::new(f64::INFINITY, 0.0));
490 assert_eq!((q.re, q.im), (0.0, 0.0));
491 }
492
493 #[test]
494 fn functions() {
495 let x = c128::new(0.5, -1.25);
496 assert!(close(x.log().exp(), x));
497 assert!(close(x.sqrt().mul(x.sqrt()), x));
498 assert!(close(x.expm1(), x.exp().sub(c128::new(1.0, 0.0))));
499 assert!(close(x.log1p(), x.add(c128::new(1.0, 0.0)).log()));
500 let (s, c) = (x.sin(), x.cos());
501 assert!(close(s.mul(s).add(c.mul(c)), c128::new(1.0, 0.0)));
502 assert!(close(x.tan(), s.div(c)));
503 let i = c128::new(0.0, 1.0);
504 assert!(close(x.tanh(), x.mul(i).tan().div(i)));
505 assert!(close(x.pow(c128::new(2.0, 0.0)), x.mul(x)));
506 assert_eq!(
507 c128::new(0.0, 0.0).pow(c128::new(0.0, 0.0)),
508 c128::new(1.0, 0.0)
509 );
510 assert_eq!(c128::new(-4.0, 0.0).sqrt(), c128::new(0.0, 2.0));
511 assert_eq!(c128::new(-4.0, -0.0).sqrt(), c128::new(0.0, -2.0));
512 assert!(close(c128::new(3.0, 4.0).sign(), c128::new(0.6, 0.8)));
513 }
514
515 #[test]
516 fn order() {
517 let (a, b) = (c64::new(1.0, 5.0), c64::new(1.0, 7.0));
518 assert!(a < b);
519 assert_eq!(a.max(b), b);
520 assert_eq!(a.min(b), a);
521 assert_eq!(c64::new(2.0, 0.0).max(b), c64::new(2.0, 0.0));
522 }
523}