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