num_complex/
lib.rs

1// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Complex numbers.
12//!
13//! ## Compatibility
14//!
15//! The `num-complex` crate is tested for rustc 1.31 and greater.
16
17#![doc(html_root_url = "https://docs.rs/num-complex/0.4")]
18#![no_std]
19
20#[cfg(any(test, feature = "std"))]
21#[cfg_attr(test, macro_use)]
22extern crate std;
23
24use core::fmt;
25#[cfg(test)]
26use core::hash;
27use core::iter::{Product, Sum};
28use core::ops::{Add, Div, Mul, Neg, Rem, Sub};
29use core::str::FromStr;
30#[cfg(feature = "std")]
31use std::error::Error;
32
33use num_traits::{Inv, MulAdd, Num, One, Pow, Signed, Zero};
34
35#[cfg(any(feature = "std", feature = "libm"))]
36use num_traits::float::Float;
37use num_traits::float::FloatCore;
38
39mod cast;
40mod pow;
41
42#[cfg(feature = "rand")]
43mod crand;
44#[cfg(feature = "rand")]
45pub use crate::crand::ComplexDistribution;
46
47// FIXME #1284: handle complex NaN & infinity etc. This
48// probably doesn't map to C's _Complex correctly.
49
50/// A complex number in Cartesian form.
51///
52/// ## Representation and Foreign Function Interface Compatibility
53///
54/// `Complex<T>` is memory layout compatible with an array `[T; 2]`.
55///
56/// Note that `Complex<F>` where F is a floating point type is **only** memory
57/// layout compatible with C's complex types, **not** necessarily calling
58/// convention compatible.  This means that for FFI you can only pass
59/// `Complex<F>` behind a pointer, not as a value.
60///
61/// ## Examples
62///
63/// Example of extern function declaration.
64///
65/// ```
66/// use num_complex::Complex;
67/// use std::os::raw::c_int;
68///
69/// extern "C" {
70///     fn zaxpy_(n: *const c_int, alpha: *const Complex<f64>,
71///               x: *const Complex<f64>, incx: *const c_int,
72///               y: *mut Complex<f64>, incy: *const c_int);
73/// }
74/// ```
75#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default)]
76#[repr(C)]
77pub struct Complex<T> {
78    /// Real portion of the complex number
79    pub re: T,
80    /// Imaginary portion of the complex number
81    pub im: T,
82}
83
84pub type Complex32 = Complex<f32>;
85pub type Complex64 = Complex<f64>;
86
87impl<T> Complex<T> {
88    /// Create a new Complex
89    #[inline]
90    pub const fn new(re: T, im: T) -> Self {
91        Complex { re, im }
92    }
93}
94
95impl<T: Clone + Num> Complex<T> {
96    /// Returns imaginary unit
97    #[inline]
98    pub fn i() -> Self {
99        Self::new(T::zero(), T::one())
100    }
101
102    /// Returns the square of the norm (since `T` doesn't necessarily
103    /// have a sqrt function), i.e. `re^2 + im^2`.
104    #[inline]
105    pub fn norm_sqr(&self) -> T {
106        self.re.clone() * self.re.clone() + self.im.clone() * self.im.clone()
107    }
108
109    /// Multiplies `self` by the scalar `t`.
110    #[inline]
111    pub fn scale(&self, t: T) -> Self {
112        Self::new(self.re.clone() * t.clone(), self.im.clone() * t)
113    }
114
115    /// Divides `self` by the scalar `t`.
116    #[inline]
117    pub fn unscale(&self, t: T) -> Self {
118        Self::new(self.re.clone() / t.clone(), self.im.clone() / t)
119    }
120
121    /// Raises `self` to an unsigned integer power.
122    #[inline]
123    pub fn powu(&self, exp: u32) -> Self {
124        Pow::pow(self, exp)
125    }
126}
127
128impl<T: Clone + Num + Neg<Output = T>> Complex<T> {
129    /// Returns the complex conjugate. i.e. `re - i im`
130    #[inline]
131    pub fn conj(&self) -> Self {
132        Self::new(self.re.clone(), -self.im.clone())
133    }
134
135    /// Returns `1/self`
136    #[inline]
137    pub fn inv(&self) -> Self {
138        let norm_sqr = self.norm_sqr();
139        Self::new(
140            self.re.clone() / norm_sqr.clone(),
141            -self.im.clone() / norm_sqr,
142        )
143    }
144
145    /// Raises `self` to a signed integer power.
146    #[inline]
147    pub fn powi(&self, exp: i32) -> Self {
148        Pow::pow(self, exp)
149    }
150}
151
152impl<T: Clone + Signed> Complex<T> {
153    /// Returns the L1 norm `|re| + |im|` -- the [Manhattan distance] from the origin.
154    ///
155    /// [Manhattan distance]: https://en.wikipedia.org/wiki/Taxicab_geometry
156    #[inline]
157    pub fn l1_norm(&self) -> T {
158        self.re.abs() + self.im.abs()
159    }
160}
161
162#[cfg(any(feature = "std", feature = "libm"))]
163impl<T: Float> Complex<T> {
164    /// Calculate |self|
165    #[inline]
166    pub fn norm(self) -> T {
167        self.re.hypot(self.im)
168    }
169    /// Calculate the principal Arg of self.
170    #[inline]
171    pub fn arg(self) -> T {
172        self.im.atan2(self.re)
173    }
174    /// Convert to polar form (r, theta), such that
175    /// `self = r * exp(i * theta)`
176    #[inline]
177    pub fn to_polar(self) -> (T, T) {
178        (self.norm(), self.arg())
179    }
180    /// Convert a polar representation into a complex number.
181    #[inline]
182    pub fn from_polar(r: T, theta: T) -> Self {
183        Self::new(r * theta.cos(), r * theta.sin())
184    }
185
186    /// Computes `e^(self)`, where `e` is the base of the natural logarithm.
187    #[inline]
188    pub fn exp(self) -> Self {
189        // formula: e^(a + bi) = e^a (cos(b) + i*sin(b))
190        // = from_polar(e^a, b)
191        Self::from_polar(self.re.exp(), self.im)
192    }
193
194    /// Computes the principal value of natural logarithm of `self`.
195    ///
196    /// This function has one branch cut:
197    ///
198    /// * `(-∞, 0]`, continuous from above.
199    ///
200    /// The branch satisfies `-π ≤ arg(ln(z)) ≤ π`.
201    #[inline]
202    pub fn ln(self) -> Self {
203        // formula: ln(z) = ln|z| + i*arg(z)
204        let (r, theta) = self.to_polar();
205        Self::new(r.ln(), theta)
206    }
207
208    /// Computes the principal value of the square root of `self`.
209    ///
210    /// This function has one branch cut:
211    ///
212    /// * `(-∞, 0)`, continuous from above.
213    ///
214    /// The branch satisfies `-π/2 ≤ arg(sqrt(z)) ≤ π/2`.
215    #[inline]
216    pub fn sqrt(self) -> Self {
217        if self.im.is_zero() {
218            if self.re.is_sign_positive() {
219                // simple positive real √r, and copy `im` for its sign
220                Self::new(self.re.sqrt(), self.im)
221            } else {
222                // √(r e^(iπ)) = √r e^(iπ/2) = i√r
223                // √(r e^(-iπ)) = √r e^(-iπ/2) = -i√r
224                let re = T::zero();
225                let im = (-self.re).sqrt();
226                if self.im.is_sign_positive() {
227                    Self::new(re, im)
228                } else {
229                    Self::new(re, -im)
230                }
231            }
232        } else if self.re.is_zero() {
233            // √(r e^(iπ/2)) = √r e^(iπ/4) = √(r/2) + i√(r/2)
234            // √(r e^(-iπ/2)) = √r e^(-iπ/4) = √(r/2) - i√(r/2)
235            let one = T::one();
236            let two = one + one;
237            let x = (self.im.abs() / two).sqrt();
238            if self.im.is_sign_positive() {
239                Self::new(x, x)
240            } else {
241                Self::new(x, -x)
242            }
243        } else {
244            // formula: sqrt(r e^(it)) = sqrt(r) e^(it/2)
245            let one = T::one();
246            let two = one + one;
247            let (r, theta) = self.to_polar();
248            Self::from_polar(r.sqrt(), theta / two)
249        }
250    }
251
252    /// Computes the principal value of the cube root of `self`.
253    ///
254    /// This function has one branch cut:
255    ///
256    /// * `(-∞, 0)`, continuous from above.
257    ///
258    /// The branch satisfies `-π/3 ≤ arg(cbrt(z)) ≤ π/3`.
259    ///
260    /// Note that this does not match the usual result for the cube root of
261    /// negative real numbers. For example, the real cube root of `-8` is `-2`,
262    /// but the principal complex cube root of `-8` is `1 + i√3`.
263    #[inline]
264    pub fn cbrt(self) -> Self {
265        if self.im.is_zero() {
266            if self.re.is_sign_positive() {
267                // simple positive real ∛r, and copy `im` for its sign
268                Self::new(self.re.cbrt(), self.im)
269            } else {
270                // ∛(r e^(iπ)) = ∛r e^(iπ/3) = ∛r/2 + i∛r√3/2
271                // ∛(r e^(-iπ)) = ∛r e^(-iπ/3) = ∛r/2 - i∛r√3/2
272                let one = T::one();
273                let two = one + one;
274                let three = two + one;
275                let re = (-self.re).cbrt() / two;
276                let im = three.sqrt() * re;
277                if self.im.is_sign_positive() {
278                    Self::new(re, im)
279                } else {
280                    Self::new(re, -im)
281                }
282            }
283        } else if self.re.is_zero() {
284            // ∛(r e^(iπ/2)) = ∛r e^(iπ/6) = ∛r√3/2 + i∛r/2
285            // ∛(r e^(-iπ/2)) = ∛r e^(-iπ/6) = ∛r√3/2 - i∛r/2
286            let one = T::one();
287            let two = one + one;
288            let three = two + one;
289            let im = self.im.abs().cbrt() / two;
290            let re = three.sqrt() * im;
291            if self.im.is_sign_positive() {
292                Self::new(re, im)
293            } else {
294                Self::new(re, -im)
295            }
296        } else {
297            // formula: cbrt(r e^(it)) = cbrt(r) e^(it/3)
298            let one = T::one();
299            let three = one + one + one;
300            let (r, theta) = self.to_polar();
301            Self::from_polar(r.cbrt(), theta / three)
302        }
303    }
304
305    /// Raises `self` to a floating point power.
306    #[inline]
307    pub fn powf(self, exp: T) -> Self {
308        // formula: x^y = (ρ e^(i θ))^y = ρ^y e^(i θ y)
309        // = from_polar(ρ^y, θ y)
310        let (r, theta) = self.to_polar();
311        Self::from_polar(r.powf(exp), theta * exp)
312    }
313
314    /// Returns the logarithm of `self` with respect to an arbitrary base.
315    #[inline]
316    pub fn log(self, base: T) -> Self {
317        // formula: log_y(x) = log_y(ρ e^(i θ))
318        // = log_y(ρ) + log_y(e^(i θ)) = log_y(ρ) + ln(e^(i θ)) / ln(y)
319        // = log_y(ρ) + i θ / ln(y)
320        let (r, theta) = self.to_polar();
321        Self::new(r.log(base), theta / base.ln())
322    }
323
324    /// Raises `self` to a complex power.
325    #[inline]
326    pub fn powc(self, exp: Self) -> Self {
327        // formula: x^y = (a + i b)^(c + i d)
328        // = (ρ e^(i θ))^c (ρ e^(i θ))^(i d)
329        //    where ρ=|x| and θ=arg(x)
330        // = ρ^c e^(−d θ) e^(i c θ) ρ^(i d)
331        // = p^c e^(−d θ) (cos(c θ)
332        //   + i sin(c θ)) (cos(d ln(ρ)) + i sin(d ln(ρ)))
333        // = p^c e^(−d θ) (
334        //   cos(c θ) cos(d ln(ρ)) − sin(c θ) sin(d ln(ρ))
335        //   + i(cos(c θ) sin(d ln(ρ)) + sin(c θ) cos(d ln(ρ))))
336        // = p^c e^(−d θ) (cos(c θ + d ln(ρ)) + i sin(c θ + d ln(ρ)))
337        // = from_polar(p^c e^(−d θ), c θ + d ln(ρ))
338        let (r, theta) = self.to_polar();
339        Self::from_polar(
340            r.powf(exp.re) * (-exp.im * theta).exp(),
341            exp.re * theta + exp.im * r.ln(),
342        )
343    }
344
345    /// Raises a floating point number to the complex power `self`.
346    #[inline]
347    pub fn expf(self, base: T) -> Self {
348        // formula: x^(a+bi) = x^a x^bi = x^a e^(b ln(x) i)
349        // = from_polar(x^a, b ln(x))
350        Self::from_polar(base.powf(self.re), self.im * base.ln())
351    }
352
353    /// Computes the sine of `self`.
354    #[inline]
355    pub fn sin(self) -> Self {
356        // formula: sin(a + bi) = sin(a)cosh(b) + i*cos(a)sinh(b)
357        Self::new(
358            self.re.sin() * self.im.cosh(),
359            self.re.cos() * self.im.sinh(),
360        )
361    }
362
363    /// Computes the cosine of `self`.
364    #[inline]
365    pub fn cos(self) -> Self {
366        // formula: cos(a + bi) = cos(a)cosh(b) - i*sin(a)sinh(b)
367        Self::new(
368            self.re.cos() * self.im.cosh(),
369            -self.re.sin() * self.im.sinh(),
370        )
371    }
372
373    /// Computes the tangent of `self`.
374    #[inline]
375    pub fn tan(self) -> Self {
376        // formula: tan(a + bi) = (sin(2a) + i*sinh(2b))/(cos(2a) + cosh(2b))
377        let (two_re, two_im) = (self.re + self.re, self.im + self.im);
378        Self::new(two_re.sin(), two_im.sinh()).unscale(two_re.cos() + two_im.cosh())
379    }
380
381    /// Computes the principal value of the inverse sine of `self`.
382    ///
383    /// This function has two branch cuts:
384    ///
385    /// * `(-∞, -1)`, continuous from above.
386    /// * `(1, ∞)`, continuous from below.
387    ///
388    /// The branch satisfies `-π/2 ≤ Re(asin(z)) ≤ π/2`.
389    #[inline]
390    pub fn asin(self) -> Self {
391        // formula: arcsin(z) = -i ln(sqrt(1-z^2) + iz)
392        let i = Self::i();
393        -i * ((Self::one() - self * self).sqrt() + i * self).ln()
394    }
395
396    /// Computes the principal value of the inverse cosine of `self`.
397    ///
398    /// This function has two branch cuts:
399    ///
400    /// * `(-∞, -1)`, continuous from above.
401    /// * `(1, ∞)`, continuous from below.
402    ///
403    /// The branch satisfies `0 ≤ Re(acos(z)) ≤ π`.
404    #[inline]
405    pub fn acos(self) -> Self {
406        // formula: arccos(z) = -i ln(i sqrt(1-z^2) + z)
407        let i = Self::i();
408        -i * (i * (Self::one() - self * self).sqrt() + self).ln()
409    }
410
411    /// Computes the principal value of the inverse tangent of `self`.
412    ///
413    /// This function has two branch cuts:
414    ///
415    /// * `(-∞i, -i]`, continuous from the left.
416    /// * `[i, ∞i)`, continuous from the right.
417    ///
418    /// The branch satisfies `-π/2 ≤ Re(atan(z)) ≤ π/2`.
419    #[inline]
420    pub fn atan(self) -> Self {
421        // formula: arctan(z) = (ln(1+iz) - ln(1-iz))/(2i)
422        let i = Self::i();
423        let one = Self::one();
424        let two = one + one;
425        if self == i {
426            return Self::new(T::zero(), T::infinity());
427        } else if self == -i {
428            return Self::new(T::zero(), -T::infinity());
429        }
430        ((one + i * self).ln() - (one - i * self).ln()) / (two * i)
431    }
432
433    /// Computes the hyperbolic sine of `self`.
434    #[inline]
435    pub fn sinh(self) -> Self {
436        // formula: sinh(a + bi) = sinh(a)cos(b) + i*cosh(a)sin(b)
437        Self::new(
438            self.re.sinh() * self.im.cos(),
439            self.re.cosh() * self.im.sin(),
440        )
441    }
442
443    /// Computes the hyperbolic cosine of `self`.
444    #[inline]
445    pub fn cosh(self) -> Self {
446        // formula: cosh(a + bi) = cosh(a)cos(b) + i*sinh(a)sin(b)
447        Self::new(
448            self.re.cosh() * self.im.cos(),
449            self.re.sinh() * self.im.sin(),
450        )
451    }
452
453    /// Computes the hyperbolic tangent of `self`.
454    #[inline]
455    pub fn tanh(self) -> Self {
456        // formula: tanh(a + bi) = (sinh(2a) + i*sin(2b))/(cosh(2a) + cos(2b))
457        let (two_re, two_im) = (self.re + self.re, self.im + self.im);
458        Self::new(two_re.sinh(), two_im.sin()).unscale(two_re.cosh() + two_im.cos())
459    }
460
461    /// Computes the principal value of inverse hyperbolic sine of `self`.
462    ///
463    /// This function has two branch cuts:
464    ///
465    /// * `(-∞i, -i)`, continuous from the left.
466    /// * `(i, ∞i)`, continuous from the right.
467    ///
468    /// The branch satisfies `-π/2 ≤ Im(asinh(z)) ≤ π/2`.
469    #[inline]
470    pub fn asinh(self) -> Self {
471        // formula: arcsinh(z) = ln(z + sqrt(1+z^2))
472        let one = Self::one();
473        (self + (one + self * self).sqrt()).ln()
474    }
475
476    /// Computes the principal value of inverse hyperbolic cosine of `self`.
477    ///
478    /// This function has one branch cut:
479    ///
480    /// * `(-∞, 1)`, continuous from above.
481    ///
482    /// The branch satisfies `-π ≤ Im(acosh(z)) ≤ π` and `0 ≤ Re(acosh(z)) < ∞`.
483    #[inline]
484    pub fn acosh(self) -> Self {
485        // formula: arccosh(z) = 2 ln(sqrt((z+1)/2) + sqrt((z-1)/2))
486        let one = Self::one();
487        let two = one + one;
488        two * (((self + one) / two).sqrt() + ((self - one) / two).sqrt()).ln()
489    }
490
491    /// Computes the principal value of inverse hyperbolic tangent of `self`.
492    ///
493    /// This function has two branch cuts:
494    ///
495    /// * `(-∞, -1]`, continuous from above.
496    /// * `[1, ∞)`, continuous from below.
497    ///
498    /// The branch satisfies `-π/2 ≤ Im(atanh(z)) ≤ π/2`.
499    #[inline]
500    pub fn atanh(self) -> Self {
501        // formula: arctanh(z) = (ln(1+z) - ln(1-z))/2
502        let one = Self::one();
503        let two = one + one;
504        if self == one {
505            return Self::new(T::infinity(), T::zero());
506        } else if self == -one {
507            return Self::new(-T::infinity(), T::zero());
508        }
509        ((one + self).ln() - (one - self).ln()) / two
510    }
511
512    /// Returns `1/self` using floating-point operations.
513    ///
514    /// This may be more accurate than the generic `self.inv()` in cases
515    /// where `self.norm_sqr()` would overflow to ∞ or underflow to 0.
516    ///
517    /// # Examples
518    ///
519    /// ```
520    /// use num_complex::Complex64;
521    /// let c = Complex64::new(1e300, 1e300);
522    ///
523    /// // The generic `inv()` will overflow.
524    /// assert!(!c.inv().is_normal());
525    ///
526    /// // But we can do better for `Float` types.
527    /// let inv = c.finv();
528    /// assert!(inv.is_normal());
529    /// println!("{:e}", inv);
530    ///
531    /// let expected = Complex64::new(5e-301, -5e-301);
532    /// assert!((inv - expected).norm() < 1e-315);
533    /// ```
534    #[inline]
535    pub fn finv(self) -> Complex<T> {
536        let norm = self.norm();
537        self.conj() / norm / norm
538    }
539
540    /// Returns `self/other` using floating-point operations.
541    ///
542    /// This may be more accurate than the generic `Div` implementation in cases
543    /// where `other.norm_sqr()` would overflow to ∞ or underflow to 0.
544    ///
545    /// # Examples
546    ///
547    /// ```
548    /// use num_complex::Complex64;
549    /// let a = Complex64::new(2.0, 3.0);
550    /// let b = Complex64::new(1e300, 1e300);
551    ///
552    /// // Generic division will overflow.
553    /// assert!(!(a / b).is_normal());
554    ///
555    /// // But we can do better for `Float` types.
556    /// let quotient = a.fdiv(b);
557    /// assert!(quotient.is_normal());
558    /// println!("{:e}", quotient);
559    ///
560    /// let expected = Complex64::new(2.5e-300, 5e-301);
561    /// assert!((quotient - expected).norm() < 1e-315);
562    /// ```
563    #[inline]
564    pub fn fdiv(self, other: Complex<T>) -> Complex<T> {
565        self * other.finv()
566    }
567}
568
569impl<T: FloatCore> Complex<T> {
570    /// Checks if the given complex number is NaN
571    #[inline]
572    pub fn is_nan(self) -> bool {
573        self.re.is_nan() || self.im.is_nan()
574    }
575
576    /// Checks if the given complex number is infinite
577    #[inline]
578    pub fn is_infinite(self) -> bool {
579        !self.is_nan() && (self.re.is_infinite() || self.im.is_infinite())
580    }
581
582    /// Checks if the given complex number is finite
583    #[inline]
584    pub fn is_finite(self) -> bool {
585        self.re.is_finite() && self.im.is_finite()
586    }
587
588    /// Checks if the given complex number is normal
589    #[inline]
590    pub fn is_normal(self) -> bool {
591        self.re.is_normal() && self.im.is_normal()
592    }
593}
594
595impl<T: Clone + Num> From<T> for Complex<T> {
596    #[inline]
597    fn from(re: T) -> Self {
598        Self::new(re, T::zero())
599    }
600}
601
602impl<'a, T: Clone + Num> From<&'a T> for Complex<T> {
603    #[inline]
604    fn from(re: &T) -> Self {
605        From::from(re.clone())
606    }
607}
608
609macro_rules! forward_ref_ref_binop {
610    (impl $imp:ident, $method:ident) => {
611        impl<'a, 'b, T: Clone + Num> $imp<&'b Complex<T>> for &'a Complex<T> {
612            type Output = Complex<T>;
613
614            #[inline]
615            fn $method(self, other: &Complex<T>) -> Self::Output {
616                self.clone().$method(other.clone())
617            }
618        }
619    };
620}
621
622macro_rules! forward_ref_val_binop {
623    (impl $imp:ident, $method:ident) => {
624        impl<'a, T: Clone + Num> $imp<Complex<T>> for &'a Complex<T> {
625            type Output = Complex<T>;
626
627            #[inline]
628            fn $method(self, other: Complex<T>) -> Self::Output {
629                self.clone().$method(other)
630            }
631        }
632    };
633}
634
635macro_rules! forward_val_ref_binop {
636    (impl $imp:ident, $method:ident) => {
637        impl<'a, T: Clone + Num> $imp<&'a Complex<T>> for Complex<T> {
638            type Output = Complex<T>;
639
640            #[inline]
641            fn $method(self, other: &Complex<T>) -> Self::Output {
642                self.$method(other.clone())
643            }
644        }
645    };
646}
647
648macro_rules! forward_all_binop {
649    (impl $imp:ident, $method:ident) => {
650        forward_ref_ref_binop!(impl $imp, $method);
651        forward_ref_val_binop!(impl $imp, $method);
652        forward_val_ref_binop!(impl $imp, $method);
653    };
654}
655
656// arithmetic
657forward_all_binop!(impl Add, add);
658
659// (a + i b) + (c + i d) == (a + c) + i (b + d)
660impl<T: Clone + Num> Add<Complex<T>> for Complex<T> {
661    type Output = Self;
662
663    #[inline]
664    fn add(self, other: Self) -> Self::Output {
665        Self::Output::new(self.re + other.re, self.im + other.im)
666    }
667}
668
669forward_all_binop!(impl Sub, sub);
670
671// (a + i b) - (c + i d) == (a - c) + i (b - d)
672impl<T: Clone + Num> Sub<Complex<T>> for Complex<T> {
673    type Output = Self;
674
675    #[inline]
676    fn sub(self, other: Self) -> Self::Output {
677        Self::Output::new(self.re - other.re, self.im - other.im)
678    }
679}
680
681forward_all_binop!(impl Mul, mul);
682
683// (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c)
684impl<T: Clone + Num> Mul<Complex<T>> for Complex<T> {
685    type Output = Self;
686
687    #[inline]
688    fn mul(self, other: Self) -> Self::Output {
689        let re = self.re.clone() * other.re.clone() - self.im.clone() * other.im.clone();
690        let im = self.re * other.im + self.im * other.re;
691        Self::Output::new(re, im)
692    }
693}
694
695// (a + i b) * (c + i d) + (e + i f) == ((a*c + e) - b*d) + i (a*d + (b*c + f))
696impl<T: Clone + Num + MulAdd<Output = T>> MulAdd<Complex<T>> for Complex<T> {
697    type Output = Complex<T>;
698
699    #[inline]
700    fn mul_add(self, other: Complex<T>, add: Complex<T>) -> Complex<T> {
701        let re = self.re.clone().mul_add(other.re.clone(), add.re)
702            - (self.im.clone() * other.im.clone()); // FIXME: use mulsub when available in rust
703        let im = self.re.mul_add(other.im, self.im.mul_add(other.re, add.im));
704        Complex::new(re, im)
705    }
706}
707impl<'a, 'b, T: Clone + Num + MulAdd<Output = T>> MulAdd<&'b Complex<T>> for &'a Complex<T> {
708    type Output = Complex<T>;
709
710    #[inline]
711    fn mul_add(self, other: &Complex<T>, add: &Complex<T>) -> Complex<T> {
712        self.clone().mul_add(other.clone(), add.clone())
713    }
714}
715
716forward_all_binop!(impl Div, div);
717
718// (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d)
719//   == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)]
720impl<T: Clone + Num> Div<Complex<T>> for Complex<T> {
721    type Output = Self;
722
723    #[inline]
724    fn div(self, other: Self) -> Self::Output {
725        let norm_sqr = other.norm_sqr();
726        let re = self.re.clone() * other.re.clone() + self.im.clone() * other.im.clone();
727        let im = self.im * other.re - self.re * other.im;
728        Self::Output::new(re / norm_sqr.clone(), im / norm_sqr)
729    }
730}
731
732forward_all_binop!(impl Rem, rem);
733
734impl<T: Clone + Num> Complex<T> {
735    /// Find the gaussian integer corresponding to the true ratio rounded towards zero.
736    fn div_trunc(&self, divisor: &Self) -> Self {
737        let Complex { re, im } = self / divisor;
738        Complex::new(re.clone() - re % T::one(), im.clone() - im % T::one())
739    }
740}
741
742impl<T: Clone + Num> Rem<Complex<T>> for Complex<T> {
743    type Output = Self;
744
745    #[inline]
746    fn rem(self, modulus: Self) -> Self::Output {
747        let gaussian = self.div_trunc(&modulus);
748        self - modulus * gaussian
749    }
750}
751
752// Op Assign
753
754mod opassign {
755    use core::ops::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign};
756
757    use num_traits::{MulAddAssign, NumAssign};
758
759    use crate::Complex;
760
761    impl<T: Clone + NumAssign> AddAssign for Complex<T> {
762        fn add_assign(&mut self, other: Self) {
763            self.re += other.re;
764            self.im += other.im;
765        }
766    }
767
768    impl<T: Clone + NumAssign> SubAssign for Complex<T> {
769        fn sub_assign(&mut self, other: Self) {
770            self.re -= other.re;
771            self.im -= other.im;
772        }
773    }
774
775    // (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c)
776    impl<T: Clone + NumAssign> MulAssign for Complex<T> {
777        fn mul_assign(&mut self, other: Self) {
778            let a = self.re.clone();
779
780            self.re *= other.re.clone();
781            self.re -= self.im.clone() * other.im.clone();
782
783            self.im *= other.re;
784            self.im += a * other.im;
785        }
786    }
787
788    // (a + i b) * (c + i d) + (e + i f) == ((a*c + e) - b*d) + i (b*c + (a*d + f))
789    impl<T: Clone + NumAssign + MulAddAssign> MulAddAssign for Complex<T> {
790        fn mul_add_assign(&mut self, other: Complex<T>, add: Complex<T>) {
791            let a = self.re.clone();
792
793            self.re.mul_add_assign(other.re.clone(), add.re); // (a*c + e)
794            self.re -= self.im.clone() * other.im.clone(); // ((a*c + e) - b*d)
795
796            let mut adf = a;
797            adf.mul_add_assign(other.im, add.im); // (a*d + f)
798            self.im.mul_add_assign(other.re, adf); // (b*c + (a*d + f))
799        }
800    }
801
802    impl<'a, 'b, T: Clone + NumAssign + MulAddAssign> MulAddAssign<&'a Complex<T>, &'b Complex<T>>
803        for Complex<T>
804    {
805        fn mul_add_assign(&mut self, other: &Complex<T>, add: &Complex<T>) {
806            self.mul_add_assign(other.clone(), add.clone());
807        }
808    }
809
810    // (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d)
811    //   == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)]
812    impl<T: Clone + NumAssign> DivAssign for Complex<T> {
813        fn div_assign(&mut self, other: Self) {
814            let a = self.re.clone();
815            let norm_sqr = other.norm_sqr();
816
817            self.re *= other.re.clone();
818            self.re += self.im.clone() * other.im.clone();
819            self.re /= norm_sqr.clone();
820
821            self.im *= other.re;
822            self.im -= a * other.im;
823            self.im /= norm_sqr;
824        }
825    }
826
827    impl<T: Clone + NumAssign> RemAssign for Complex<T> {
828        fn rem_assign(&mut self, modulus: Self) {
829            let gaussian = self.div_trunc(&modulus);
830            *self -= modulus * gaussian;
831        }
832    }
833
834    impl<T: Clone + NumAssign> AddAssign<T> for Complex<T> {
835        fn add_assign(&mut self, other: T) {
836            self.re += other;
837        }
838    }
839
840    impl<T: Clone + NumAssign> SubAssign<T> for Complex<T> {
841        fn sub_assign(&mut self, other: T) {
842            self.re -= other;
843        }
844    }
845
846    impl<T: Clone + NumAssign> MulAssign<T> for Complex<T> {
847        fn mul_assign(&mut self, other: T) {
848            self.re *= other.clone();
849            self.im *= other;
850        }
851    }
852
853    impl<T: Clone + NumAssign> DivAssign<T> for Complex<T> {
854        fn div_assign(&mut self, other: T) {
855            self.re /= other.clone();
856            self.im /= other;
857        }
858    }
859
860    impl<T: Clone + NumAssign> RemAssign<T> for Complex<T> {
861        fn rem_assign(&mut self, other: T) {
862            self.re %= other.clone();
863            self.im %= other;
864        }
865    }
866
867    macro_rules! forward_op_assign {
868        (impl $imp:ident, $method:ident) => {
869            impl<'a, T: Clone + NumAssign> $imp<&'a Complex<T>> for Complex<T> {
870                #[inline]
871                fn $method(&mut self, other: &Self) {
872                    self.$method(other.clone())
873                }
874            }
875            impl<'a, T: Clone + NumAssign> $imp<&'a T> for Complex<T> {
876                #[inline]
877                fn $method(&mut self, other: &T) {
878                    self.$method(other.clone())
879                }
880            }
881        };
882    }
883
884    forward_op_assign!(impl AddAssign, add_assign);
885    forward_op_assign!(impl SubAssign, sub_assign);
886    forward_op_assign!(impl MulAssign, mul_assign);
887    forward_op_assign!(impl DivAssign, div_assign);
888    forward_op_assign!(impl RemAssign, rem_assign);
889}
890
891impl<T: Clone + Num + Neg<Output = T>> Neg for Complex<T> {
892    type Output = Self;
893
894    #[inline]
895    fn neg(self) -> Self::Output {
896        Self::Output::new(-self.re, -self.im)
897    }
898}
899
900impl<'a, T: Clone + Num + Neg<Output = T>> Neg for &'a Complex<T> {
901    type Output = Complex<T>;
902
903    #[inline]
904    fn neg(self) -> Self::Output {
905        -self.clone()
906    }
907}
908
909impl<T: Clone + Num + Neg<Output = T>> Inv for Complex<T> {
910    type Output = Self;
911
912    #[inline]
913    fn inv(self) -> Self::Output {
914        (&self).inv()
915    }
916}
917
918impl<'a, T: Clone + Num + Neg<Output = T>> Inv for &'a Complex<T> {
919    type Output = Complex<T>;
920
921    #[inline]
922    fn inv(self) -> Self::Output {
923        self.inv()
924    }
925}
926
927macro_rules! real_arithmetic {
928    (@forward $imp:ident::$method:ident for $($real:ident),*) => (
929        impl<'a, T: Clone + Num> $imp<&'a T> for Complex<T> {
930            type Output = Complex<T>;
931
932            #[inline]
933            fn $method(self, other: &T) -> Self::Output {
934                self.$method(other.clone())
935            }
936        }
937        impl<'a, T: Clone + Num> $imp<T> for &'a Complex<T> {
938            type Output = Complex<T>;
939
940            #[inline]
941            fn $method(self, other: T) -> Self::Output {
942                self.clone().$method(other)
943            }
944        }
945        impl<'a, 'b, T: Clone + Num> $imp<&'a T> for &'b Complex<T> {
946            type Output = Complex<T>;
947
948            #[inline]
949            fn $method(self, other: &T) -> Self::Output {
950                self.clone().$method(other.clone())
951            }
952        }
953        $(
954            impl<'a> $imp<&'a Complex<$real>> for $real {
955                type Output = Complex<$real>;
956
957                #[inline]
958                fn $method(self, other: &Complex<$real>) -> Complex<$real> {
959                    self.$method(other.clone())
960                }
961            }
962            impl<'a> $imp<Complex<$real>> for &'a $real {
963                type Output = Complex<$real>;
964
965                #[inline]
966                fn $method(self, other: Complex<$real>) -> Complex<$real> {
967                    self.clone().$method(other)
968                }
969            }
970            impl<'a, 'b> $imp<&'a Complex<$real>> for &'b $real {
971                type Output = Complex<$real>;
972
973                #[inline]
974                fn $method(self, other: &Complex<$real>) -> Complex<$real> {
975                    self.clone().$method(other.clone())
976                }
977            }
978        )*
979    );
980    ($($real:ident),*) => (
981        real_arithmetic!(@forward Add::add for $($real),*);
982        real_arithmetic!(@forward Sub::sub for $($real),*);
983        real_arithmetic!(@forward Mul::mul for $($real),*);
984        real_arithmetic!(@forward Div::div for $($real),*);
985        real_arithmetic!(@forward Rem::rem for $($real),*);
986
987        $(
988            impl Add<Complex<$real>> for $real {
989                type Output = Complex<$real>;
990
991                #[inline]
992                fn add(self, other: Complex<$real>) -> Self::Output {
993                    Self::Output::new(self + other.re, other.im)
994                }
995            }
996
997            impl Sub<Complex<$real>> for $real {
998                type Output = Complex<$real>;
999
1000                #[inline]
1001                fn sub(self, other: Complex<$real>) -> Self::Output  {
1002                    Self::Output::new(self - other.re, $real::zero() - other.im)
1003                }
1004            }
1005
1006            impl Mul<Complex<$real>> for $real {
1007                type Output = Complex<$real>;
1008
1009                #[inline]
1010                fn mul(self, other: Complex<$real>) -> Self::Output {
1011                    Self::Output::new(self * other.re, self * other.im)
1012                }
1013            }
1014
1015            impl Div<Complex<$real>> for $real {
1016                type Output = Complex<$real>;
1017
1018                #[inline]
1019                fn div(self, other: Complex<$real>) -> Self::Output {
1020                    // a / (c + i d) == [a * (c - i d)] / (c*c + d*d)
1021                    let norm_sqr = other.norm_sqr();
1022                    Self::Output::new(self * other.re / norm_sqr.clone(),
1023                                      $real::zero() - self * other.im / norm_sqr)
1024                }
1025            }
1026
1027            impl Rem<Complex<$real>> for $real {
1028                type Output = Complex<$real>;
1029
1030                #[inline]
1031                fn rem(self, other: Complex<$real>) -> Self::Output {
1032                    Self::Output::new(self, Self::zero()) % other
1033                }
1034            }
1035        )*
1036    );
1037}
1038
1039impl<T: Clone + Num> Add<T> for Complex<T> {
1040    type Output = Complex<T>;
1041
1042    #[inline]
1043    fn add(self, other: T) -> Self::Output {
1044        Self::Output::new(self.re + other, self.im)
1045    }
1046}
1047
1048impl<T: Clone + Num> Sub<T> for Complex<T> {
1049    type Output = Complex<T>;
1050
1051    #[inline]
1052    fn sub(self, other: T) -> Self::Output {
1053        Self::Output::new(self.re - other, self.im)
1054    }
1055}
1056
1057impl<T: Clone + Num> Mul<T> for Complex<T> {
1058    type Output = Complex<T>;
1059
1060    #[inline]
1061    fn mul(self, other: T) -> Self::Output {
1062        Self::Output::new(self.re * other.clone(), self.im * other)
1063    }
1064}
1065
1066impl<T: Clone + Num> Div<T> for Complex<T> {
1067    type Output = Self;
1068
1069    #[inline]
1070    fn div(self, other: T) -> Self::Output {
1071        Self::Output::new(self.re / other.clone(), self.im / other)
1072    }
1073}
1074
1075impl<T: Clone + Num> Rem<T> for Complex<T> {
1076    type Output = Complex<T>;
1077
1078    #[inline]
1079    fn rem(self, other: T) -> Self::Output {
1080        Self::Output::new(self.re % other.clone(), self.im % other)
1081    }
1082}
1083
1084real_arithmetic!(usize, u8, u16, u32, u64, u128, isize, i8, i16, i32, i64, i128, f32, f64);
1085
1086// constants
1087impl<T: Clone + Num> Zero for Complex<T> {
1088    #[inline]
1089    fn zero() -> Self {
1090        Self::new(Zero::zero(), Zero::zero())
1091    }
1092
1093    #[inline]
1094    fn is_zero(&self) -> bool {
1095        self.re.is_zero() && self.im.is_zero()
1096    }
1097
1098    #[inline]
1099    fn set_zero(&mut self) {
1100        self.re.set_zero();
1101        self.im.set_zero();
1102    }
1103}
1104
1105impl<T: Clone + Num> One for Complex<T> {
1106    #[inline]
1107    fn one() -> Self {
1108        Self::new(One::one(), Zero::zero())
1109    }
1110
1111    #[inline]
1112    fn is_one(&self) -> bool {
1113        self.re.is_one() && self.im.is_zero()
1114    }
1115
1116    #[inline]
1117    fn set_one(&mut self) {
1118        self.re.set_one();
1119        self.im.set_zero();
1120    }
1121}
1122
1123macro_rules! write_complex {
1124    ($f:ident, $t:expr, $prefix:expr, $re:expr, $im:expr, $T:ident) => {{
1125        let abs_re = if $re < Zero::zero() {
1126            $T::zero() - $re.clone()
1127        } else {
1128            $re.clone()
1129        };
1130        let abs_im = if $im < Zero::zero() {
1131            $T::zero() - $im.clone()
1132        } else {
1133            $im.clone()
1134        };
1135
1136        return if let Some(prec) = $f.precision() {
1137            fmt_re_im(
1138                $f,
1139                $re < $T::zero(),
1140                $im < $T::zero(),
1141                format_args!(concat!("{:.1$", $t, "}"), abs_re, prec),
1142                format_args!(concat!("{:.1$", $t, "}"), abs_im, prec),
1143            )
1144        } else {
1145            fmt_re_im(
1146                $f,
1147                $re < $T::zero(),
1148                $im < $T::zero(),
1149                format_args!(concat!("{:", $t, "}"), abs_re),
1150                format_args!(concat!("{:", $t, "}"), abs_im),
1151            )
1152        };
1153
1154        fn fmt_re_im(
1155            f: &mut fmt::Formatter<'_>,
1156            re_neg: bool,
1157            im_neg: bool,
1158            real: fmt::Arguments<'_>,
1159            imag: fmt::Arguments<'_>,
1160        ) -> fmt::Result {
1161            let prefix = if f.alternate() { $prefix } else { "" };
1162            let sign = if re_neg {
1163                "-"
1164            } else if f.sign_plus() {
1165                "+"
1166            } else {
1167                ""
1168            };
1169
1170            if im_neg {
1171                fmt_complex(
1172                    f,
1173                    format_args!(
1174                        "{}{pre}{re}-{pre}{im}i",
1175                        sign,
1176                        re = real,
1177                        im = imag,
1178                        pre = prefix
1179                    ),
1180                )
1181            } else {
1182                fmt_complex(
1183                    f,
1184                    format_args!(
1185                        "{}{pre}{re}+{pre}{im}i",
1186                        sign,
1187                        re = real,
1188                        im = imag,
1189                        pre = prefix
1190                    ),
1191                )
1192            }
1193        }
1194
1195        #[cfg(feature = "std")]
1196        // Currently, we can only apply width using an intermediate `String` (and thus `std`)
1197        fn fmt_complex(f: &mut fmt::Formatter<'_>, complex: fmt::Arguments<'_>) -> fmt::Result {
1198            use std::string::ToString;
1199            if let Some(width) = f.width() {
1200                write!(f, "{0: >1$}", complex.to_string(), width)
1201            } else {
1202                write!(f, "{}", complex)
1203            }
1204        }
1205
1206        #[cfg(not(feature = "std"))]
1207        fn fmt_complex(f: &mut fmt::Formatter<'_>, complex: fmt::Arguments<'_>) -> fmt::Result {
1208            write!(f, "{}", complex)
1209        }
1210    }};
1211}
1212
1213// string conversions
1214impl<T> fmt::Display for Complex<T>
1215where
1216    T: fmt::Display + Num + PartialOrd + Clone,
1217{
1218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1219        write_complex!(f, "", "", self.re, self.im, T)
1220    }
1221}
1222
1223impl<T> fmt::LowerExp for Complex<T>
1224where
1225    T: fmt::LowerExp + Num + PartialOrd + Clone,
1226{
1227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1228        write_complex!(f, "e", "", self.re, self.im, T)
1229    }
1230}
1231
1232impl<T> fmt::UpperExp for Complex<T>
1233where
1234    T: fmt::UpperExp + Num + PartialOrd + Clone,
1235{
1236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237        write_complex!(f, "E", "", self.re, self.im, T)
1238    }
1239}
1240
1241impl<T> fmt::LowerHex for Complex<T>
1242where
1243    T: fmt::LowerHex + Num + PartialOrd + Clone,
1244{
1245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1246        write_complex!(f, "x", "0x", self.re, self.im, T)
1247    }
1248}
1249
1250impl<T> fmt::UpperHex for Complex<T>
1251where
1252    T: fmt::UpperHex + Num + PartialOrd + Clone,
1253{
1254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1255        write_complex!(f, "X", "0x", self.re, self.im, T)
1256    }
1257}
1258
1259impl<T> fmt::Octal for Complex<T>
1260where
1261    T: fmt::Octal + Num + PartialOrd + Clone,
1262{
1263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1264        write_complex!(f, "o", "0o", self.re, self.im, T)
1265    }
1266}
1267
1268impl<T> fmt::Binary for Complex<T>
1269where
1270    T: fmt::Binary + Num + PartialOrd + Clone,
1271{
1272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273        write_complex!(f, "b", "0b", self.re, self.im, T)
1274    }
1275}
1276
1277#[allow(deprecated)] // `trim_left_matches` and `trim_right_matches` since 1.33
1278fn from_str_generic<T, E, F>(s: &str, from: F) -> Result<Complex<T>, ParseComplexError<E>>
1279where
1280    F: Fn(&str) -> Result<T, E>,
1281    T: Clone + Num,
1282{
1283    let imag = match s.rfind('j') {
1284        None => 'i',
1285        _ => 'j',
1286    };
1287
1288    let mut neg_b = false;
1289    let mut a = s;
1290    let mut b = "";
1291
1292    for (i, w) in s.as_bytes().windows(2).enumerate() {
1293        let p = w[0];
1294        let c = w[1];
1295
1296        // ignore '+'/'-' if part of an exponent
1297        if (c == b'+' || c == b'-') && !(p == b'e' || p == b'E') {
1298            // trim whitespace around the separator
1299            a = &s[..=i].trim_right_matches(char::is_whitespace);
1300            b = &s[i + 2..].trim_left_matches(char::is_whitespace);
1301            neg_b = c == b'-';
1302
1303            if b.is_empty() || (neg_b && b.starts_with('-')) {
1304                return Err(ParseComplexError::new());
1305            }
1306            break;
1307        }
1308    }
1309
1310    // split off real and imaginary parts
1311    if b.is_empty() {
1312        // input was either pure real or pure imaginary
1313        b = if a.ends_with(imag) { "0" } else { "0i" };
1314    }
1315
1316    let re;
1317    let neg_re;
1318    let im;
1319    let neg_im;
1320    if a.ends_with(imag) {
1321        im = a;
1322        neg_im = false;
1323        re = b;
1324        neg_re = neg_b;
1325    } else if b.ends_with(imag) {
1326        re = a;
1327        neg_re = false;
1328        im = b;
1329        neg_im = neg_b;
1330    } else {
1331        return Err(ParseComplexError::new());
1332    }
1333
1334    // parse re
1335    let re = from(re).map_err(ParseComplexError::from_error)?;
1336    let re = if neg_re { T::zero() - re } else { re };
1337
1338    // pop imaginary unit off
1339    let mut im = &im[..im.len() - 1];
1340    // handle im == "i" or im == "-i"
1341    if im.is_empty() || im == "+" {
1342        im = "1";
1343    } else if im == "-" {
1344        im = "-1";
1345    }
1346
1347    // parse im
1348    let im = from(im).map_err(ParseComplexError::from_error)?;
1349    let im = if neg_im { T::zero() - im } else { im };
1350
1351    Ok(Complex::new(re, im))
1352}
1353
1354impl<T> FromStr for Complex<T>
1355where
1356    T: FromStr + Num + Clone,
1357{
1358    type Err = ParseComplexError<T::Err>;
1359
1360    /// Parses `a +/- bi`; `ai +/- b`; `a`; or `bi` where `a` and `b` are of type `T`
1361    fn from_str(s: &str) -> Result<Self, Self::Err> {
1362        from_str_generic(s, T::from_str)
1363    }
1364}
1365
1366impl<T: Num + Clone> Num for Complex<T> {
1367    type FromStrRadixErr = ParseComplexError<T::FromStrRadixErr>;
1368
1369    /// Parses `a +/- bi`; `ai +/- b`; `a`; or `bi` where `a` and `b` are of type `T`
1370    fn from_str_radix(s: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
1371        from_str_generic(s, |x| -> Result<T, T::FromStrRadixErr> {
1372            T::from_str_radix(x, radix)
1373        })
1374    }
1375}
1376
1377impl<T: Num + Clone> Sum for Complex<T> {
1378    fn sum<I>(iter: I) -> Self
1379    where
1380        I: Iterator<Item = Self>,
1381    {
1382        iter.fold(Self::zero(), |acc, c| acc + c)
1383    }
1384}
1385
1386impl<'a, T: 'a + Num + Clone> Sum<&'a Complex<T>> for Complex<T> {
1387    fn sum<I>(iter: I) -> Self
1388    where
1389        I: Iterator<Item = &'a Complex<T>>,
1390    {
1391        iter.fold(Self::zero(), |acc, c| acc + c)
1392    }
1393}
1394
1395impl<T: Num + Clone> Product for Complex<T> {
1396    fn product<I>(iter: I) -> Self
1397    where
1398        I: Iterator<Item = Self>,
1399    {
1400        iter.fold(Self::one(), |acc, c| acc * c)
1401    }
1402}
1403
1404impl<'a, T: 'a + Num + Clone> Product<&'a Complex<T>> for Complex<T> {
1405    fn product<I>(iter: I) -> Self
1406    where
1407        I: Iterator<Item = &'a Complex<T>>,
1408    {
1409        iter.fold(Self::one(), |acc, c| acc * c)
1410    }
1411}
1412
1413#[cfg(feature = "serde")]
1414impl<T> serde::Serialize for Complex<T>
1415where
1416    T: serde::Serialize,
1417{
1418    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1419    where
1420        S: serde::Serializer,
1421    {
1422        (&self.re, &self.im).serialize(serializer)
1423    }
1424}
1425
1426#[cfg(feature = "serde")]
1427impl<'de, T> serde::Deserialize<'de> for Complex<T>
1428where
1429    T: serde::Deserialize<'de> + Num + Clone,
1430{
1431    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1432    where
1433        D: serde::Deserializer<'de>,
1434    {
1435        let (re, im) = serde::Deserialize::deserialize(deserializer)?;
1436        Ok(Self::new(re, im))
1437    }
1438}
1439
1440#[derive(Debug, PartialEq)]
1441pub struct ParseComplexError<E> {
1442    kind: ComplexErrorKind<E>,
1443}
1444
1445#[derive(Debug, PartialEq)]
1446enum ComplexErrorKind<E> {
1447    ParseError(E),
1448    ExprError,
1449}
1450
1451impl<E> ParseComplexError<E> {
1452    fn new() -> Self {
1453        ParseComplexError {
1454            kind: ComplexErrorKind::ExprError,
1455        }
1456    }
1457
1458    fn from_error(error: E) -> Self {
1459        ParseComplexError {
1460            kind: ComplexErrorKind::ParseError(error),
1461        }
1462    }
1463}
1464
1465#[cfg(feature = "std")]
1466impl<E: Error> Error for ParseComplexError<E> {
1467    #[allow(deprecated)]
1468    fn description(&self) -> &str {
1469        match self.kind {
1470            ComplexErrorKind::ParseError(ref e) => e.description(),
1471            ComplexErrorKind::ExprError => "invalid or unsupported complex expression",
1472        }
1473    }
1474}
1475
1476impl<E: fmt::Display> fmt::Display for ParseComplexError<E> {
1477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1478        match self.kind {
1479            ComplexErrorKind::ParseError(ref e) => e.fmt(f),
1480            ComplexErrorKind::ExprError => "invalid or unsupported complex expression".fmt(f),
1481        }
1482    }
1483}
1484
1485#[cfg(test)]
1486fn hash<T: hash::Hash>(x: &T) -> u64 {
1487    use std::collections::hash_map::RandomState;
1488    use std::hash::{BuildHasher, Hasher};
1489    let mut hasher = <RandomState as BuildHasher>::Hasher::new();
1490    x.hash(&mut hasher);
1491    hasher.finish()
1492}
1493
1494#[cfg(test)]
1495mod test {
1496    #![allow(non_upper_case_globals)]
1497
1498    use super::{Complex, Complex64};
1499    use core::f64;
1500    use core::str::FromStr;
1501
1502    use std::string::{String, ToString};
1503
1504    use num_traits::{Num, One, Zero};
1505
1506    pub const _0_0i: Complex64 = Complex { re: 0.0, im: 0.0 };
1507    pub const _1_0i: Complex64 = Complex { re: 1.0, im: 0.0 };
1508    pub const _1_1i: Complex64 = Complex { re: 1.0, im: 1.0 };
1509    pub const _0_1i: Complex64 = Complex { re: 0.0, im: 1.0 };
1510    pub const _neg1_1i: Complex64 = Complex { re: -1.0, im: 1.0 };
1511    pub const _05_05i: Complex64 = Complex { re: 0.5, im: 0.5 };
1512    pub const all_consts: [Complex64; 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i];
1513    pub const _4_2i: Complex64 = Complex { re: 4.0, im: 2.0 };
1514
1515    #[test]
1516    fn test_consts() {
1517        // check our constants are what Complex::new creates
1518        fn test(c: Complex64, r: f64, i: f64) {
1519            assert_eq!(c, Complex::new(r, i));
1520        }
1521        test(_0_0i, 0.0, 0.0);
1522        test(_1_0i, 1.0, 0.0);
1523        test(_1_1i, 1.0, 1.0);
1524        test(_neg1_1i, -1.0, 1.0);
1525        test(_05_05i, 0.5, 0.5);
1526
1527        assert_eq!(_0_0i, Zero::zero());
1528        assert_eq!(_1_0i, One::one());
1529    }
1530
1531    #[test]
1532    fn test_scale_unscale() {
1533        assert_eq!(_05_05i.scale(2.0), _1_1i);
1534        assert_eq!(_1_1i.unscale(2.0), _05_05i);
1535        for &c in all_consts.iter() {
1536            assert_eq!(c.scale(2.0).unscale(2.0), c);
1537        }
1538    }
1539
1540    #[test]
1541    fn test_conj() {
1542        for &c in all_consts.iter() {
1543            assert_eq!(c.conj(), Complex::new(c.re, -c.im));
1544            assert_eq!(c.conj().conj(), c);
1545        }
1546    }
1547
1548    #[test]
1549    fn test_inv() {
1550        assert_eq!(_1_1i.inv(), _05_05i.conj());
1551        assert_eq!(_1_0i.inv(), _1_0i.inv());
1552    }
1553
1554    #[test]
1555    #[should_panic]
1556    fn test_divide_by_zero_natural() {
1557        let n = Complex::new(2, 3);
1558        let d = Complex::new(0, 0);
1559        let _x = n / d;
1560    }
1561
1562    #[test]
1563    fn test_inv_zero() {
1564        // FIXME #20: should this really fail, or just NaN?
1565        assert!(_0_0i.inv().is_nan());
1566    }
1567
1568    #[test]
1569    #[allow(clippy::float_cmp)]
1570    fn test_l1_norm() {
1571        assert_eq!(_0_0i.l1_norm(), 0.0);
1572        assert_eq!(_1_0i.l1_norm(), 1.0);
1573        assert_eq!(_1_1i.l1_norm(), 2.0);
1574        assert_eq!(_0_1i.l1_norm(), 1.0);
1575        assert_eq!(_neg1_1i.l1_norm(), 2.0);
1576        assert_eq!(_05_05i.l1_norm(), 1.0);
1577        assert_eq!(_4_2i.l1_norm(), 6.0);
1578    }
1579
1580    #[test]
1581    fn test_pow() {
1582        for c in all_consts.iter() {
1583            assert_eq!(c.powi(0), _1_0i);
1584            let mut pos = _1_0i;
1585            let mut neg = _1_0i;
1586            for i in 1i32..20 {
1587                pos *= c;
1588                assert_eq!(pos, c.powi(i));
1589                if c.is_zero() {
1590                    assert!(c.powi(-i).is_nan());
1591                } else {
1592                    neg /= c;
1593                    assert_eq!(neg, c.powi(-i));
1594                }
1595            }
1596        }
1597    }
1598
1599    #[cfg(any(feature = "std", feature = "libm"))]
1600    mod float {
1601        use super::*;
1602        use num_traits::{Float, Pow};
1603
1604        #[test]
1605        #[cfg_attr(target_arch = "x86", ignore)]
1606        // FIXME #7158: (maybe?) currently failing on x86.
1607        #[allow(clippy::float_cmp)]
1608        fn test_norm() {
1609            fn test(c: Complex64, ns: f64) {
1610                assert_eq!(c.norm_sqr(), ns);
1611                assert_eq!(c.norm(), ns.sqrt())
1612            }
1613            test(_0_0i, 0.0);
1614            test(_1_0i, 1.0);
1615            test(_1_1i, 2.0);
1616            test(_neg1_1i, 2.0);
1617            test(_05_05i, 0.5);
1618        }
1619
1620        #[test]
1621        fn test_arg() {
1622            fn test(c: Complex64, arg: f64) {
1623                assert!((c.arg() - arg).abs() < 1.0e-6)
1624            }
1625            test(_1_0i, 0.0);
1626            test(_1_1i, 0.25 * f64::consts::PI);
1627            test(_neg1_1i, 0.75 * f64::consts::PI);
1628            test(_05_05i, 0.25 * f64::consts::PI);
1629        }
1630
1631        #[test]
1632        fn test_polar_conv() {
1633            fn test(c: Complex64) {
1634                let (r, theta) = c.to_polar();
1635                assert!((c - Complex::from_polar(r, theta)).norm() < 1e-6);
1636            }
1637            for &c in all_consts.iter() {
1638                test(c);
1639            }
1640        }
1641
1642        fn close(a: Complex64, b: Complex64) -> bool {
1643            close_to_tol(a, b, 1e-10)
1644        }
1645
1646        fn close_to_tol(a: Complex64, b: Complex64, tol: f64) -> bool {
1647            // returns true if a and b are reasonably close
1648            let close = (a == b) || (a - b).norm() < tol;
1649            if !close {
1650                println!("{:?} != {:?}", a, b);
1651            }
1652            close
1653        }
1654
1655        #[test]
1656        fn test_exp() {
1657            assert!(close(_1_0i.exp(), _1_0i.scale(f64::consts::E)));
1658            assert!(close(_0_0i.exp(), _1_0i));
1659            assert!(close(_0_1i.exp(), Complex::new(1.0.cos(), 1.0.sin())));
1660            assert!(close(_05_05i.exp() * _05_05i.exp(), _1_1i.exp()));
1661            assert!(close(
1662                _0_1i.scale(-f64::consts::PI).exp(),
1663                _1_0i.scale(-1.0)
1664            ));
1665            for &c in all_consts.iter() {
1666                // e^conj(z) = conj(e^z)
1667                assert!(close(c.conj().exp(), c.exp().conj()));
1668                // e^(z + 2 pi i) = e^z
1669                assert!(close(
1670                    c.exp(),
1671                    (c + _0_1i.scale(f64::consts::PI * 2.0)).exp()
1672                ));
1673            }
1674        }
1675
1676        #[test]
1677        fn test_ln() {
1678            assert!(close(_1_0i.ln(), _0_0i));
1679            assert!(close(_0_1i.ln(), _0_1i.scale(f64::consts::PI / 2.0)));
1680            assert!(close(_0_0i.ln(), Complex::new(f64::neg_infinity(), 0.0)));
1681            assert!(close(
1682                (_neg1_1i * _05_05i).ln(),
1683                _neg1_1i.ln() + _05_05i.ln()
1684            ));
1685            for &c in all_consts.iter() {
1686                // ln(conj(z() = conj(ln(z))
1687                assert!(close(c.conj().ln(), c.ln().conj()));
1688                // for this branch, -pi <= arg(ln(z)) <= pi
1689                assert!(-f64::consts::PI <= c.ln().arg() && c.ln().arg() <= f64::consts::PI);
1690            }
1691        }
1692
1693        #[test]
1694        fn test_powc() {
1695            let a = Complex::new(2.0, -3.0);
1696            let b = Complex::new(3.0, 0.0);
1697            assert!(close(a.powc(b), a.powf(b.re)));
1698            assert!(close(b.powc(a), a.expf(b.re)));
1699            let c = Complex::new(1.0 / 3.0, 0.1);
1700            assert!(close_to_tol(
1701                a.powc(c),
1702                Complex::new(1.65826, -0.33502),
1703                1e-5
1704            ));
1705        }
1706
1707        #[test]
1708        fn test_powf() {
1709            let c = Complex64::new(2.0, -1.0);
1710            let expected = Complex64::new(-0.8684746, -16.695934);
1711            assert!(close_to_tol(c.powf(3.5), expected, 1e-5));
1712            assert!(close_to_tol(Pow::pow(c, 3.5_f64), expected, 1e-5));
1713            assert!(close_to_tol(Pow::pow(c, 3.5_f32), expected, 1e-5));
1714        }
1715
1716        #[test]
1717        fn test_log() {
1718            let c = Complex::new(2.0, -1.0);
1719            let r = c.log(10.0);
1720            assert!(close_to_tol(r, Complex::new(0.349485, -0.20135958), 1e-5));
1721        }
1722
1723        #[test]
1724        fn test_some_expf_cases() {
1725            let c = Complex::new(2.0, -1.0);
1726            let r = c.expf(10.0);
1727            assert!(close_to_tol(r, Complex::new(-66.82015, -74.39803), 1e-5));
1728
1729            let c = Complex::new(5.0, -2.0);
1730            let r = c.expf(3.4);
1731            assert!(close_to_tol(r, Complex::new(-349.25, -290.63), 1e-2));
1732
1733            let c = Complex::new(-1.5, 2.0 / 3.0);
1734            let r = c.expf(1.0 / 3.0);
1735            assert!(close_to_tol(r, Complex::new(3.8637, -3.4745), 1e-2));
1736        }
1737
1738        #[test]
1739        fn test_sqrt() {
1740            assert!(close(_0_0i.sqrt(), _0_0i));
1741            assert!(close(_1_0i.sqrt(), _1_0i));
1742            assert!(close(Complex::new(-1.0, 0.0).sqrt(), _0_1i));
1743            assert!(close(Complex::new(-1.0, -0.0).sqrt(), _0_1i.scale(-1.0)));
1744            assert!(close(_0_1i.sqrt(), _05_05i.scale(2.0.sqrt())));
1745            for &c in all_consts.iter() {
1746                // sqrt(conj(z() = conj(sqrt(z))
1747                assert!(close(c.conj().sqrt(), c.sqrt().conj()));
1748                // for this branch, -pi/2 <= arg(sqrt(z)) <= pi/2
1749                assert!(
1750                    -f64::consts::FRAC_PI_2 <= c.sqrt().arg()
1751                        && c.sqrt().arg() <= f64::consts::FRAC_PI_2
1752                );
1753                // sqrt(z) * sqrt(z) = z
1754                assert!(close(c.sqrt() * c.sqrt(), c));
1755            }
1756        }
1757
1758        #[test]
1759        fn test_sqrt_real() {
1760            for n in (0..100).map(f64::from) {
1761                // √(n² + 0i) = n + 0i
1762                let n2 = n * n;
1763                assert_eq!(Complex64::new(n2, 0.0).sqrt(), Complex64::new(n, 0.0));
1764                // √(-n² + 0i) = 0 + ni
1765                assert_eq!(Complex64::new(-n2, 0.0).sqrt(), Complex64::new(0.0, n));
1766                // √(-n² - 0i) = 0 - ni
1767                assert_eq!(Complex64::new(-n2, -0.0).sqrt(), Complex64::new(0.0, -n));
1768            }
1769        }
1770
1771        #[test]
1772        fn test_sqrt_imag() {
1773            for n in (0..100).map(f64::from) {
1774                // √(0 + n²i) = n e^(iπ/4)
1775                let n2 = n * n;
1776                assert!(close(
1777                    Complex64::new(0.0, n2).sqrt(),
1778                    Complex64::from_polar(n, f64::consts::FRAC_PI_4)
1779                ));
1780                // √(0 - n²i) = n e^(-iπ/4)
1781                assert!(close(
1782                    Complex64::new(0.0, -n2).sqrt(),
1783                    Complex64::from_polar(n, -f64::consts::FRAC_PI_4)
1784                ));
1785            }
1786        }
1787
1788        #[test]
1789        fn test_cbrt() {
1790            assert!(close(_0_0i.cbrt(), _0_0i));
1791            assert!(close(_1_0i.cbrt(), _1_0i));
1792            assert!(close(
1793                Complex::new(-1.0, 0.0).cbrt(),
1794                Complex::new(0.5, 0.75.sqrt())
1795            ));
1796            assert!(close(
1797                Complex::new(-1.0, -0.0).cbrt(),
1798                Complex::new(0.5, -(0.75.sqrt()))
1799            ));
1800            assert!(close(_0_1i.cbrt(), Complex::new(0.75.sqrt(), 0.5)));
1801            assert!(close(_0_1i.conj().cbrt(), Complex::new(0.75.sqrt(), -0.5)));
1802            for &c in all_consts.iter() {
1803                // cbrt(conj(z() = conj(cbrt(z))
1804                assert!(close(c.conj().cbrt(), c.cbrt().conj()));
1805                // for this branch, -pi/3 <= arg(cbrt(z)) <= pi/3
1806                assert!(
1807                    -f64::consts::FRAC_PI_3 <= c.cbrt().arg()
1808                        && c.cbrt().arg() <= f64::consts::FRAC_PI_3
1809                );
1810                // cbrt(z) * cbrt(z) cbrt(z) = z
1811                assert!(close(c.cbrt() * c.cbrt() * c.cbrt(), c));
1812            }
1813        }
1814
1815        #[test]
1816        fn test_cbrt_real() {
1817            for n in (0..100).map(f64::from) {
1818                // ∛(n³ + 0i) = n + 0i
1819                let n3 = n * n * n;
1820                assert!(close(
1821                    Complex64::new(n3, 0.0).cbrt(),
1822                    Complex64::new(n, 0.0)
1823                ));
1824                // ∛(-n³ + 0i) = n e^(iπ/3)
1825                assert!(close(
1826                    Complex64::new(-n3, 0.0).cbrt(),
1827                    Complex64::from_polar(n, f64::consts::FRAC_PI_3)
1828                ));
1829                // ∛(-n³ - 0i) = n e^(-iπ/3)
1830                assert!(close(
1831                    Complex64::new(-n3, -0.0).cbrt(),
1832                    Complex64::from_polar(n, -f64::consts::FRAC_PI_3)
1833                ));
1834            }
1835        }
1836
1837        #[test]
1838        fn test_cbrt_imag() {
1839            for n in (0..100).map(f64::from) {
1840                // ∛(0 + n³i) = n e^(iπ/6)
1841                let n3 = n * n * n;
1842                assert!(close(
1843                    Complex64::new(0.0, n3).cbrt(),
1844                    Complex64::from_polar(n, f64::consts::FRAC_PI_6)
1845                ));
1846                // ∛(0 - n³i) = n e^(-iπ/6)
1847                assert!(close(
1848                    Complex64::new(0.0, -n3).cbrt(),
1849                    Complex64::from_polar(n, -f64::consts::FRAC_PI_6)
1850                ));
1851            }
1852        }
1853
1854        #[test]
1855        fn test_sin() {
1856            assert!(close(_0_0i.sin(), _0_0i));
1857            assert!(close(_1_0i.scale(f64::consts::PI * 2.0).sin(), _0_0i));
1858            assert!(close(_0_1i.sin(), _0_1i.scale(1.0.sinh())));
1859            for &c in all_consts.iter() {
1860                // sin(conj(z)) = conj(sin(z))
1861                assert!(close(c.conj().sin(), c.sin().conj()));
1862                // sin(-z) = -sin(z)
1863                assert!(close(c.scale(-1.0).sin(), c.sin().scale(-1.0)));
1864            }
1865        }
1866
1867        #[test]
1868        fn test_cos() {
1869            assert!(close(_0_0i.cos(), _1_0i));
1870            assert!(close(_1_0i.scale(f64::consts::PI * 2.0).cos(), _1_0i));
1871            assert!(close(_0_1i.cos(), _1_0i.scale(1.0.cosh())));
1872            for &c in all_consts.iter() {
1873                // cos(conj(z)) = conj(cos(z))
1874                assert!(close(c.conj().cos(), c.cos().conj()));
1875                // cos(-z) = cos(z)
1876                assert!(close(c.scale(-1.0).cos(), c.cos()));
1877            }
1878        }
1879
1880        #[test]
1881        fn test_tan() {
1882            assert!(close(_0_0i.tan(), _0_0i));
1883            assert!(close(_1_0i.scale(f64::consts::PI / 4.0).tan(), _1_0i));
1884            assert!(close(_1_0i.scale(f64::consts::PI).tan(), _0_0i));
1885            for &c in all_consts.iter() {
1886                // tan(conj(z)) = conj(tan(z))
1887                assert!(close(c.conj().tan(), c.tan().conj()));
1888                // tan(-z) = -tan(z)
1889                assert!(close(c.scale(-1.0).tan(), c.tan().scale(-1.0)));
1890            }
1891        }
1892
1893        #[test]
1894        fn test_asin() {
1895            assert!(close(_0_0i.asin(), _0_0i));
1896            assert!(close(_1_0i.asin(), _1_0i.scale(f64::consts::PI / 2.0)));
1897            assert!(close(
1898                _1_0i.scale(-1.0).asin(),
1899                _1_0i.scale(-f64::consts::PI / 2.0)
1900            ));
1901            assert!(close(_0_1i.asin(), _0_1i.scale((1.0 + 2.0.sqrt()).ln())));
1902            for &c in all_consts.iter() {
1903                // asin(conj(z)) = conj(asin(z))
1904                assert!(close(c.conj().asin(), c.asin().conj()));
1905                // asin(-z) = -asin(z)
1906                assert!(close(c.scale(-1.0).asin(), c.asin().scale(-1.0)));
1907                // for this branch, -pi/2 <= asin(z).re <= pi/2
1908                assert!(
1909                    -f64::consts::PI / 2.0 <= c.asin().re && c.asin().re <= f64::consts::PI / 2.0
1910                );
1911            }
1912        }
1913
1914        #[test]
1915        fn test_acos() {
1916            assert!(close(_0_0i.acos(), _1_0i.scale(f64::consts::PI / 2.0)));
1917            assert!(close(_1_0i.acos(), _0_0i));
1918            assert!(close(
1919                _1_0i.scale(-1.0).acos(),
1920                _1_0i.scale(f64::consts::PI)
1921            ));
1922            assert!(close(
1923                _0_1i.acos(),
1924                Complex::new(f64::consts::PI / 2.0, (2.0.sqrt() - 1.0).ln())
1925            ));
1926            for &c in all_consts.iter() {
1927                // acos(conj(z)) = conj(acos(z))
1928                assert!(close(c.conj().acos(), c.acos().conj()));
1929                // for this branch, 0 <= acos(z).re <= pi
1930                assert!(0.0 <= c.acos().re && c.acos().re <= f64::consts::PI);
1931            }
1932        }
1933
1934        #[test]
1935        fn test_atan() {
1936            assert!(close(_0_0i.atan(), _0_0i));
1937            assert!(close(_1_0i.atan(), _1_0i.scale(f64::consts::PI / 4.0)));
1938            assert!(close(
1939                _1_0i.scale(-1.0).atan(),
1940                _1_0i.scale(-f64::consts::PI / 4.0)
1941            ));
1942            assert!(close(_0_1i.atan(), Complex::new(0.0, f64::infinity())));
1943            for &c in all_consts.iter() {
1944                // atan(conj(z)) = conj(atan(z))
1945                assert!(close(c.conj().atan(), c.atan().conj()));
1946                // atan(-z) = -atan(z)
1947                assert!(close(c.scale(-1.0).atan(), c.atan().scale(-1.0)));
1948                // for this branch, -pi/2 <= atan(z).re <= pi/2
1949                assert!(
1950                    -f64::consts::PI / 2.0 <= c.atan().re && c.atan().re <= f64::consts::PI / 2.0
1951                );
1952            }
1953        }
1954
1955        #[test]
1956        fn test_sinh() {
1957            assert!(close(_0_0i.sinh(), _0_0i));
1958            assert!(close(
1959                _1_0i.sinh(),
1960                _1_0i.scale((f64::consts::E - 1.0 / f64::consts::E) / 2.0)
1961            ));
1962            assert!(close(_0_1i.sinh(), _0_1i.scale(1.0.sin())));
1963            for &c in all_consts.iter() {
1964                // sinh(conj(z)) = conj(sinh(z))
1965                assert!(close(c.conj().sinh(), c.sinh().conj()));
1966                // sinh(-z) = -sinh(z)
1967                assert!(close(c.scale(-1.0).sinh(), c.sinh().scale(-1.0)));
1968            }
1969        }
1970
1971        #[test]
1972        fn test_cosh() {
1973            assert!(close(_0_0i.cosh(), _1_0i));
1974            assert!(close(
1975                _1_0i.cosh(),
1976                _1_0i.scale((f64::consts::E + 1.0 / f64::consts::E) / 2.0)
1977            ));
1978            assert!(close(_0_1i.cosh(), _1_0i.scale(1.0.cos())));
1979            for &c in all_consts.iter() {
1980                // cosh(conj(z)) = conj(cosh(z))
1981                assert!(close(c.conj().cosh(), c.cosh().conj()));
1982                // cosh(-z) = cosh(z)
1983                assert!(close(c.scale(-1.0).cosh(), c.cosh()));
1984            }
1985        }
1986
1987        #[test]
1988        fn test_tanh() {
1989            assert!(close(_0_0i.tanh(), _0_0i));
1990            assert!(close(
1991                _1_0i.tanh(),
1992                _1_0i.scale((f64::consts::E.powi(2) - 1.0) / (f64::consts::E.powi(2) + 1.0))
1993            ));
1994            assert!(close(_0_1i.tanh(), _0_1i.scale(1.0.tan())));
1995            for &c in all_consts.iter() {
1996                // tanh(conj(z)) = conj(tanh(z))
1997                assert!(close(c.conj().tanh(), c.conj().tanh()));
1998                // tanh(-z) = -tanh(z)
1999                assert!(close(c.scale(-1.0).tanh(), c.tanh().scale(-1.0)));
2000            }
2001        }
2002
2003        #[test]
2004        fn test_asinh() {
2005            assert!(close(_0_0i.asinh(), _0_0i));
2006            assert!(close(_1_0i.asinh(), _1_0i.scale(1.0 + 2.0.sqrt()).ln()));
2007            assert!(close(_0_1i.asinh(), _0_1i.scale(f64::consts::PI / 2.0)));
2008            assert!(close(
2009                _0_1i.asinh().scale(-1.0),
2010                _0_1i.scale(-f64::consts::PI / 2.0)
2011            ));
2012            for &c in all_consts.iter() {
2013                // asinh(conj(z)) = conj(asinh(z))
2014                assert!(close(c.conj().asinh(), c.conj().asinh()));
2015                // asinh(-z) = -asinh(z)
2016                assert!(close(c.scale(-1.0).asinh(), c.asinh().scale(-1.0)));
2017                // for this branch, -pi/2 <= asinh(z).im <= pi/2
2018                assert!(
2019                    -f64::consts::PI / 2.0 <= c.asinh().im && c.asinh().im <= f64::consts::PI / 2.0
2020                );
2021            }
2022        }
2023
2024        #[test]
2025        fn test_acosh() {
2026            assert!(close(_0_0i.acosh(), _0_1i.scale(f64::consts::PI / 2.0)));
2027            assert!(close(_1_0i.acosh(), _0_0i));
2028            assert!(close(
2029                _1_0i.scale(-1.0).acosh(),
2030                _0_1i.scale(f64::consts::PI)
2031            ));
2032            for &c in all_consts.iter() {
2033                // acosh(conj(z)) = conj(acosh(z))
2034                assert!(close(c.conj().acosh(), c.conj().acosh()));
2035                // for this branch, -pi <= acosh(z).im <= pi and 0 <= acosh(z).re
2036                assert!(
2037                    -f64::consts::PI <= c.acosh().im
2038                        && c.acosh().im <= f64::consts::PI
2039                        && 0.0 <= c.cosh().re
2040                );
2041            }
2042        }
2043
2044        #[test]
2045        fn test_atanh() {
2046            assert!(close(_0_0i.atanh(), _0_0i));
2047            assert!(close(_0_1i.atanh(), _0_1i.scale(f64::consts::PI / 4.0)));
2048            assert!(close(_1_0i.atanh(), Complex::new(f64::infinity(), 0.0)));
2049            for &c in all_consts.iter() {
2050                // atanh(conj(z)) = conj(atanh(z))
2051                assert!(close(c.conj().atanh(), c.conj().atanh()));
2052                // atanh(-z) = -atanh(z)
2053                assert!(close(c.scale(-1.0).atanh(), c.atanh().scale(-1.0)));
2054                // for this branch, -pi/2 <= atanh(z).im <= pi/2
2055                assert!(
2056                    -f64::consts::PI / 2.0 <= c.atanh().im && c.atanh().im <= f64::consts::PI / 2.0
2057                );
2058            }
2059        }
2060
2061        #[test]
2062        fn test_exp_ln() {
2063            for &c in all_consts.iter() {
2064                // e^ln(z) = z
2065                assert!(close(c.ln().exp(), c));
2066            }
2067        }
2068
2069        #[test]
2070        fn test_trig_to_hyperbolic() {
2071            for &c in all_consts.iter() {
2072                // sin(iz) = i sinh(z)
2073                assert!(close((_0_1i * c).sin(), _0_1i * c.sinh()));
2074                // cos(iz) = cosh(z)
2075                assert!(close((_0_1i * c).cos(), c.cosh()));
2076                // tan(iz) = i tanh(z)
2077                assert!(close((_0_1i * c).tan(), _0_1i * c.tanh()));
2078            }
2079        }
2080
2081        #[test]
2082        fn test_trig_identities() {
2083            for &c in all_consts.iter() {
2084                // tan(z) = sin(z)/cos(z)
2085                assert!(close(c.tan(), c.sin() / c.cos()));
2086                // sin(z)^2 + cos(z)^2 = 1
2087                assert!(close(c.sin() * c.sin() + c.cos() * c.cos(), _1_0i));
2088
2089                // sin(asin(z)) = z
2090                assert!(close(c.asin().sin(), c));
2091                // cos(acos(z)) = z
2092                assert!(close(c.acos().cos(), c));
2093                // tan(atan(z)) = z
2094                // i and -i are branch points
2095                if c != _0_1i && c != _0_1i.scale(-1.0) {
2096                    assert!(close(c.atan().tan(), c));
2097                }
2098
2099                // sin(z) = (e^(iz) - e^(-iz))/(2i)
2100                assert!(close(
2101                    ((_0_1i * c).exp() - (_0_1i * c).exp().inv()) / _0_1i.scale(2.0),
2102                    c.sin()
2103                ));
2104                // cos(z) = (e^(iz) + e^(-iz))/2
2105                assert!(close(
2106                    ((_0_1i * c).exp() + (_0_1i * c).exp().inv()).unscale(2.0),
2107                    c.cos()
2108                ));
2109                // tan(z) = i (1 - e^(2iz))/(1 + e^(2iz))
2110                assert!(close(
2111                    _0_1i * (_1_0i - (_0_1i * c).scale(2.0).exp())
2112                        / (_1_0i + (_0_1i * c).scale(2.0).exp()),
2113                    c.tan()
2114                ));
2115            }
2116        }
2117
2118        #[test]
2119        fn test_hyperbolic_identites() {
2120            for &c in all_consts.iter() {
2121                // tanh(z) = sinh(z)/cosh(z)
2122                assert!(close(c.tanh(), c.sinh() / c.cosh()));
2123                // cosh(z)^2 - sinh(z)^2 = 1
2124                assert!(close(c.cosh() * c.cosh() - c.sinh() * c.sinh(), _1_0i));
2125
2126                // sinh(asinh(z)) = z
2127                assert!(close(c.asinh().sinh(), c));
2128                // cosh(acosh(z)) = z
2129                assert!(close(c.acosh().cosh(), c));
2130                // tanh(atanh(z)) = z
2131                // 1 and -1 are branch points
2132                if c != _1_0i && c != _1_0i.scale(-1.0) {
2133                    assert!(close(c.atanh().tanh(), c));
2134                }
2135
2136                // sinh(z) = (e^z - e^(-z))/2
2137                assert!(close((c.exp() - c.exp().inv()).unscale(2.0), c.sinh()));
2138                // cosh(z) = (e^z + e^(-z))/2
2139                assert!(close((c.exp() + c.exp().inv()).unscale(2.0), c.cosh()));
2140                // tanh(z) = ( e^(2z) - 1)/(e^(2z) + 1)
2141                assert!(close(
2142                    (c.scale(2.0).exp() - _1_0i) / (c.scale(2.0).exp() + _1_0i),
2143                    c.tanh()
2144                ));
2145            }
2146        }
2147    }
2148
2149    // Test both a + b and a += b
2150    macro_rules! test_a_op_b {
2151        ($a:ident + $b:expr, $answer:expr) => {
2152            assert_eq!($a + $b, $answer);
2153            assert_eq!(
2154                {
2155                    let mut x = $a;
2156                    x += $b;
2157                    x
2158                },
2159                $answer
2160            );
2161        };
2162        ($a:ident - $b:expr, $answer:expr) => {
2163            assert_eq!($a - $b, $answer);
2164            assert_eq!(
2165                {
2166                    let mut x = $a;
2167                    x -= $b;
2168                    x
2169                },
2170                $answer
2171            );
2172        };
2173        ($a:ident * $b:expr, $answer:expr) => {
2174            assert_eq!($a * $b, $answer);
2175            assert_eq!(
2176                {
2177                    let mut x = $a;
2178                    x *= $b;
2179                    x
2180                },
2181                $answer
2182            );
2183        };
2184        ($a:ident / $b:expr, $answer:expr) => {
2185            assert_eq!($a / $b, $answer);
2186            assert_eq!(
2187                {
2188                    let mut x = $a;
2189                    x /= $b;
2190                    x
2191                },
2192                $answer
2193            );
2194        };
2195        ($a:ident % $b:expr, $answer:expr) => {
2196            assert_eq!($a % $b, $answer);
2197            assert_eq!(
2198                {
2199                    let mut x = $a;
2200                    x %= $b;
2201                    x
2202                },
2203                $answer
2204            );
2205        };
2206    }
2207
2208    // Test both a + b and a + &b
2209    macro_rules! test_op {
2210        ($a:ident $op:tt $b:expr, $answer:expr) => {
2211            test_a_op_b!($a $op $b, $answer);
2212            test_a_op_b!($a $op &$b, $answer);
2213        };
2214    }
2215
2216    mod complex_arithmetic {
2217        use super::{_05_05i, _0_0i, _0_1i, _1_0i, _1_1i, _4_2i, _neg1_1i, all_consts};
2218        use num_traits::{MulAdd, MulAddAssign, Zero};
2219
2220        #[test]
2221        fn test_add() {
2222            test_op!(_05_05i + _05_05i, _1_1i);
2223            test_op!(_0_1i + _1_0i, _1_1i);
2224            test_op!(_1_0i + _neg1_1i, _0_1i);
2225
2226            for &c in all_consts.iter() {
2227                test_op!(_0_0i + c, c);
2228                test_op!(c + _0_0i, c);
2229            }
2230        }
2231
2232        #[test]
2233        fn test_sub() {
2234            test_op!(_05_05i - _05_05i, _0_0i);
2235            test_op!(_0_1i - _1_0i, _neg1_1i);
2236            test_op!(_0_1i - _neg1_1i, _1_0i);
2237
2238            for &c in all_consts.iter() {
2239                test_op!(c - _0_0i, c);
2240                test_op!(c - c, _0_0i);
2241            }
2242        }
2243
2244        #[test]
2245        fn test_mul() {
2246            test_op!(_05_05i * _05_05i, _0_1i.unscale(2.0));
2247            test_op!(_1_1i * _0_1i, _neg1_1i);
2248
2249            // i^2 & i^4
2250            test_op!(_0_1i * _0_1i, -_1_0i);
2251            assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i);
2252
2253            for &c in all_consts.iter() {
2254                test_op!(c * _1_0i, c);
2255                test_op!(_1_0i * c, c);
2256            }
2257        }
2258
2259        #[test]
2260        #[cfg(any(feature = "std", feature = "libm"))]
2261        fn test_mul_add_float() {
2262            assert_eq!(_05_05i.mul_add(_05_05i, _0_0i), _05_05i * _05_05i + _0_0i);
2263            assert_eq!(_05_05i * _05_05i + _0_0i, _05_05i.mul_add(_05_05i, _0_0i));
2264            assert_eq!(_0_1i.mul_add(_0_1i, _0_1i), _neg1_1i);
2265            assert_eq!(_1_0i.mul_add(_1_0i, _1_0i), _1_0i * _1_0i + _1_0i);
2266            assert_eq!(_1_0i * _1_0i + _1_0i, _1_0i.mul_add(_1_0i, _1_0i));
2267
2268            let mut x = _1_0i;
2269            x.mul_add_assign(_1_0i, _1_0i);
2270            assert_eq!(x, _1_0i * _1_0i + _1_0i);
2271
2272            for &a in &all_consts {
2273                for &b in &all_consts {
2274                    for &c in &all_consts {
2275                        let abc = a * b + c;
2276                        assert_eq!(a.mul_add(b, c), abc);
2277                        let mut x = a;
2278                        x.mul_add_assign(b, c);
2279                        assert_eq!(x, abc);
2280                    }
2281                }
2282            }
2283        }
2284
2285        #[test]
2286        fn test_mul_add() {
2287            use super::Complex;
2288            const _0_0i: Complex<i32> = Complex { re: 0, im: 0 };
2289            const _1_0i: Complex<i32> = Complex { re: 1, im: 0 };
2290            const _1_1i: Complex<i32> = Complex { re: 1, im: 1 };
2291            const _0_1i: Complex<i32> = Complex { re: 0, im: 1 };
2292            const _neg1_1i: Complex<i32> = Complex { re: -1, im: 1 };
2293            const all_consts: [Complex<i32>; 5] = [_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i];
2294
2295            assert_eq!(_1_0i.mul_add(_1_0i, _0_0i), _1_0i * _1_0i + _0_0i);
2296            assert_eq!(_1_0i * _1_0i + _0_0i, _1_0i.mul_add(_1_0i, _0_0i));
2297            assert_eq!(_0_1i.mul_add(_0_1i, _0_1i), _neg1_1i);
2298            assert_eq!(_1_0i.mul_add(_1_0i, _1_0i), _1_0i * _1_0i + _1_0i);
2299            assert_eq!(_1_0i * _1_0i + _1_0i, _1_0i.mul_add(_1_0i, _1_0i));
2300
2301            let mut x = _1_0i;
2302            x.mul_add_assign(_1_0i, _1_0i);
2303            assert_eq!(x, _1_0i * _1_0i + _1_0i);
2304
2305            for &a in &all_consts {
2306                for &b in &all_consts {
2307                    for &c in &all_consts {
2308                        let abc = a * b + c;
2309                        assert_eq!(a.mul_add(b, c), abc);
2310                        let mut x = a;
2311                        x.mul_add_assign(b, c);
2312                        assert_eq!(x, abc);
2313                    }
2314                }
2315            }
2316        }
2317
2318        #[test]
2319        fn test_div() {
2320            test_op!(_neg1_1i / _0_1i, _1_1i);
2321            for &c in all_consts.iter() {
2322                if c != Zero::zero() {
2323                    test_op!(c / c, _1_0i);
2324                }
2325            }
2326        }
2327
2328        #[test]
2329        fn test_rem() {
2330            test_op!(_neg1_1i % _0_1i, _0_0i);
2331            test_op!(_4_2i % _0_1i, _0_0i);
2332            test_op!(_05_05i % _0_1i, _05_05i);
2333            test_op!(_05_05i % _1_1i, _05_05i);
2334            assert_eq!((_4_2i + _05_05i) % _0_1i, _05_05i);
2335            assert_eq!((_4_2i + _05_05i) % _1_1i, _05_05i);
2336        }
2337
2338        #[test]
2339        fn test_neg() {
2340            assert_eq!(-_1_0i + _0_1i, _neg1_1i);
2341            assert_eq!((-_0_1i) * _0_1i, _1_0i);
2342            for &c in all_consts.iter() {
2343                assert_eq!(-(-c), c);
2344            }
2345        }
2346    }
2347
2348    mod real_arithmetic {
2349        use super::super::Complex;
2350        use super::{_4_2i, _neg1_1i};
2351
2352        #[test]
2353        fn test_add() {
2354            test_op!(_4_2i + 0.5, Complex::new(4.5, 2.0));
2355            assert_eq!(0.5 + _4_2i, Complex::new(4.5, 2.0));
2356        }
2357
2358        #[test]
2359        fn test_sub() {
2360            test_op!(_4_2i - 0.5, Complex::new(3.5, 2.0));
2361            assert_eq!(0.5 - _4_2i, Complex::new(-3.5, -2.0));
2362        }
2363
2364        #[test]
2365        fn test_mul() {
2366            assert_eq!(_4_2i * 0.5, Complex::new(2.0, 1.0));
2367            assert_eq!(0.5 * _4_2i, Complex::new(2.0, 1.0));
2368        }
2369
2370        #[test]
2371        fn test_div() {
2372            assert_eq!(_4_2i / 0.5, Complex::new(8.0, 4.0));
2373            assert_eq!(0.5 / _4_2i, Complex::new(0.1, -0.05));
2374        }
2375
2376        #[test]
2377        fn test_rem() {
2378            assert_eq!(_4_2i % 2.0, Complex::new(0.0, 0.0));
2379            assert_eq!(_4_2i % 3.0, Complex::new(1.0, 2.0));
2380            assert_eq!(3.0 % _4_2i, Complex::new(3.0, 0.0));
2381            assert_eq!(_neg1_1i % 2.0, _neg1_1i);
2382            assert_eq!(-_4_2i % 3.0, Complex::new(-1.0, -2.0));
2383        }
2384
2385        #[test]
2386        fn test_div_rem_gaussian() {
2387            // These would overflow with `norm_sqr` division.
2388            let max = Complex::new(255u8, 255u8);
2389            assert_eq!(max / 200, Complex::new(1, 1));
2390            assert_eq!(max % 200, Complex::new(55, 55));
2391        }
2392    }
2393
2394    #[test]
2395    fn test_to_string() {
2396        fn test(c: Complex64, s: String) {
2397            assert_eq!(c.to_string(), s);
2398        }
2399        test(_0_0i, "0+0i".to_string());
2400        test(_1_0i, "1+0i".to_string());
2401        test(_0_1i, "0+1i".to_string());
2402        test(_1_1i, "1+1i".to_string());
2403        test(_neg1_1i, "-1+1i".to_string());
2404        test(-_neg1_1i, "1-1i".to_string());
2405        test(_05_05i, "0.5+0.5i".to_string());
2406    }
2407
2408    #[test]
2409    fn test_string_formatting() {
2410        let a = Complex::new(1.23456, 123.456);
2411        assert_eq!(format!("{}", a), "1.23456+123.456i");
2412        assert_eq!(format!("{:.2}", a), "1.23+123.46i");
2413        assert_eq!(format!("{:.2e}", a), "1.23e0+1.23e2i");
2414        assert_eq!(format!("{:+.2E}", a), "+1.23E0+1.23E2i");
2415        #[cfg(feature = "std")]
2416        assert_eq!(format!("{:+20.2E}", a), "     +1.23E0+1.23E2i");
2417
2418        let b = Complex::new(0x80, 0xff);
2419        assert_eq!(format!("{:X}", b), "80+FFi");
2420        assert_eq!(format!("{:#x}", b), "0x80+0xffi");
2421        assert_eq!(format!("{:+#b}", b), "+0b10000000+0b11111111i");
2422        assert_eq!(format!("{:+#o}", b), "+0o200+0o377i");
2423        #[cfg(feature = "std")]
2424        assert_eq!(format!("{:+#16o}", b), "   +0o200+0o377i");
2425
2426        let c = Complex::new(-10, -10000);
2427        assert_eq!(format!("{}", c), "-10-10000i");
2428        #[cfg(feature = "std")]
2429        assert_eq!(format!("{:16}", c), "      -10-10000i");
2430    }
2431
2432    #[test]
2433    fn test_hash() {
2434        let a = Complex::new(0i32, 0i32);
2435        let b = Complex::new(1i32, 0i32);
2436        let c = Complex::new(0i32, 1i32);
2437        assert!(crate::hash(&a) != crate::hash(&b));
2438        assert!(crate::hash(&b) != crate::hash(&c));
2439        assert!(crate::hash(&c) != crate::hash(&a));
2440    }
2441
2442    #[test]
2443    fn test_hashset() {
2444        use std::collections::HashSet;
2445        let a = Complex::new(0i32, 0i32);
2446        let b = Complex::new(1i32, 0i32);
2447        let c = Complex::new(0i32, 1i32);
2448
2449        let set: HashSet<_> = [a, b, c].iter().cloned().collect();
2450        assert!(set.contains(&a));
2451        assert!(set.contains(&b));
2452        assert!(set.contains(&c));
2453        assert!(!set.contains(&(a + b + c)));
2454    }
2455
2456    #[test]
2457    fn test_is_nan() {
2458        assert!(!_1_1i.is_nan());
2459        let a = Complex::new(f64::NAN, f64::NAN);
2460        assert!(a.is_nan());
2461    }
2462
2463    #[test]
2464    fn test_is_nan_special_cases() {
2465        let a = Complex::new(0f64, f64::NAN);
2466        let b = Complex::new(f64::NAN, 0f64);
2467        assert!(a.is_nan());
2468        assert!(b.is_nan());
2469    }
2470
2471    #[test]
2472    fn test_is_infinite() {
2473        let a = Complex::new(2f64, f64::INFINITY);
2474        assert!(a.is_infinite());
2475    }
2476
2477    #[test]
2478    fn test_is_finite() {
2479        assert!(_1_1i.is_finite())
2480    }
2481
2482    #[test]
2483    fn test_is_normal() {
2484        let a = Complex::new(0f64, f64::NAN);
2485        let b = Complex::new(2f64, f64::INFINITY);
2486        assert!(!a.is_normal());
2487        assert!(!b.is_normal());
2488        assert!(_1_1i.is_normal());
2489    }
2490
2491    #[test]
2492    fn test_from_str() {
2493        fn test(z: Complex64, s: &str) {
2494            assert_eq!(FromStr::from_str(s), Ok(z));
2495        }
2496        test(_0_0i, "0 + 0i");
2497        test(_0_0i, "0+0j");
2498        test(_0_0i, "0 - 0j");
2499        test(_0_0i, "0-0i");
2500        test(_0_0i, "0i + 0");
2501        test(_0_0i, "0");
2502        test(_0_0i, "-0");
2503        test(_0_0i, "0i");
2504        test(_0_0i, "0j");
2505        test(_0_0i, "+0j");
2506        test(_0_0i, "-0i");
2507
2508        test(_1_0i, "1 + 0i");
2509        test(_1_0i, "1+0j");
2510        test(_1_0i, "1 - 0j");
2511        test(_1_0i, "+1-0i");
2512        test(_1_0i, "-0j+1");
2513        test(_1_0i, "1");
2514
2515        test(_1_1i, "1 + i");
2516        test(_1_1i, "1+j");
2517        test(_1_1i, "1 + 1j");
2518        test(_1_1i, "1+1i");
2519        test(_1_1i, "i + 1");
2520        test(_1_1i, "1i+1");
2521        test(_1_1i, "+j+1");
2522
2523        test(_0_1i, "0 + i");
2524        test(_0_1i, "0+j");
2525        test(_0_1i, "-0 + j");
2526        test(_0_1i, "-0+i");
2527        test(_0_1i, "0 + 1i");
2528        test(_0_1i, "0+1j");
2529        test(_0_1i, "-0 + 1j");
2530        test(_0_1i, "-0+1i");
2531        test(_0_1i, "j + 0");
2532        test(_0_1i, "i");
2533        test(_0_1i, "j");
2534        test(_0_1i, "1j");
2535
2536        test(_neg1_1i, "-1 + i");
2537        test(_neg1_1i, "-1+j");
2538        test(_neg1_1i, "-1 + 1j");
2539        test(_neg1_1i, "-1+1i");
2540        test(_neg1_1i, "1i-1");
2541        test(_neg1_1i, "j + -1");
2542
2543        test(_05_05i, "0.5 + 0.5i");
2544        test(_05_05i, "0.5+0.5j");
2545        test(_05_05i, "5e-1+0.5j");
2546        test(_05_05i, "5E-1 + 0.5j");
2547        test(_05_05i, "5E-1i + 0.5");
2548        test(_05_05i, "0.05e+1j + 50E-2");
2549    }
2550
2551    #[test]
2552    fn test_from_str_radix() {
2553        fn test(z: Complex64, s: &str, radix: u32) {
2554            let res: Result<Complex64, <Complex64 as Num>::FromStrRadixErr> =
2555                Num::from_str_radix(s, radix);
2556            assert_eq!(res.unwrap(), z)
2557        }
2558        test(_4_2i, "4+2i", 10);
2559        test(Complex::new(15.0, 32.0), "F+20i", 16);
2560        test(Complex::new(15.0, 32.0), "1111+100000i", 2);
2561        test(Complex::new(-15.0, -32.0), "-F-20i", 16);
2562        test(Complex::new(-15.0, -32.0), "-1111-100000i", 2);
2563    }
2564
2565    #[test]
2566    fn test_from_str_fail() {
2567        fn test(s: &str) {
2568            let complex: Result<Complex64, _> = FromStr::from_str(s);
2569            assert!(
2570                complex.is_err(),
2571                "complex {:?} -> {:?} should be an error",
2572                s,
2573                complex
2574            );
2575        }
2576        test("foo");
2577        test("6E");
2578        test("0 + 2.718");
2579        test("1 - -2i");
2580        test("314e-2ij");
2581        test("4.3j - i");
2582        test("1i - 2i");
2583        test("+ 1 - 3.0i");
2584    }
2585
2586    #[test]
2587    fn test_sum() {
2588        let v = vec![_0_1i, _1_0i];
2589        assert_eq!(v.iter().sum::<Complex64>(), _1_1i);
2590        assert_eq!(v.into_iter().sum::<Complex64>(), _1_1i);
2591    }
2592
2593    #[test]
2594    fn test_prod() {
2595        let v = vec![_0_1i, _1_0i];
2596        assert_eq!(v.iter().product::<Complex64>(), _0_1i);
2597        assert_eq!(v.into_iter().product::<Complex64>(), _0_1i);
2598    }
2599
2600    #[test]
2601    fn test_zero() {
2602        let zero = Complex64::zero();
2603        assert!(zero.is_zero());
2604
2605        let mut c = Complex::new(1.23, 4.56);
2606        assert!(!c.is_zero());
2607        assert_eq!(c + zero, c);
2608
2609        c.set_zero();
2610        assert!(c.is_zero());
2611    }
2612
2613    #[test]
2614    fn test_one() {
2615        let one = Complex64::one();
2616        assert!(one.is_one());
2617
2618        let mut c = Complex::new(1.23, 4.56);
2619        assert!(!c.is_one());
2620        assert_eq!(c * one, c);
2621
2622        c.set_one();
2623        assert!(c.is_one());
2624    }
2625
2626    #[test]
2627    #[allow(clippy::float_cmp)]
2628    fn test_const() {
2629        const R: f64 = 12.3;
2630        const I: f64 = -4.5;
2631        const C: Complex64 = Complex::new(R, I);
2632
2633        assert_eq!(C.re, 12.3);
2634        assert_eq!(C.im, -4.5);
2635    }
2636}