1#![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)]
22extern crate std;
23
24extern crate num_traits as traits;
25
26#[cfg(feature = "serde")]
27extern crate serde;
28
29#[cfg(feature = "rand")]
30extern crate rand;
31
32use core::fmt;
33#[cfg(test)]
34use core::hash;
35use core::iter::{Product, Sum};
36use core::ops::{Add, Div, Mul, Neg, Rem, Sub};
37use core::str::FromStr;
38#[cfg(feature = "std")]
39use std::error::Error;
40
41use traits::{Inv, MulAdd, Num, One, Pow, Signed, Zero};
42
43#[cfg(feature = "std")]
44use traits::float::Float;
45use traits::float::FloatCore;
46
47mod cast;
48mod pow;
49
50#[cfg(feature = "rand")]
51mod crand;
52#[cfg(feature = "rand")]
53pub use crand::ComplexDistribution;
54
55#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default)]
84#[repr(C)]
85pub struct Complex<T> {
86 pub re: T,
88 pub im: T,
90}
91
92pub type Complex32 = Complex<f32>;
93pub type Complex64 = Complex<f64>;
94
95impl<T> Complex<T> {
96 #[cfg(has_const_fn)]
97 #[inline]
99 pub const fn new(re: T, im: T) -> Self {
100 Complex { re: re, im: im }
101 }
102
103 #[cfg(not(has_const_fn))]
104 #[inline]
106 pub fn new(re: T, im: T) -> Self {
107 Complex { re: re, im: im }
108 }
109}
110
111impl<T: Clone + Num> Complex<T> {
112 #[inline]
114 pub fn i() -> Self {
115 Self::new(T::zero(), T::one())
116 }
117
118 #[inline]
121 pub fn norm_sqr(&self) -> T {
122 self.re.clone() * self.re.clone() + self.im.clone() * self.im.clone()
123 }
124
125 #[inline]
127 pub fn scale(&self, t: T) -> Self {
128 Self::new(self.re.clone() * t.clone(), self.im.clone() * t)
129 }
130
131 #[inline]
133 pub fn unscale(&self, t: T) -> Self {
134 Self::new(self.re.clone() / t.clone(), self.im.clone() / t)
135 }
136
137 #[inline]
139 pub fn powu(&self, exp: u32) -> Self {
140 Pow::pow(self, exp)
141 }
142}
143
144impl<T: Clone + Num + Neg<Output = T>> Complex<T> {
145 #[inline]
147 pub fn conj(&self) -> Self {
148 Self::new(self.re.clone(), -self.im.clone())
149 }
150
151 #[inline]
153 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 #[inline]
163 pub fn powi(&self, exp: i32) -> Self {
164 Pow::pow(self, exp)
165 }
166}
167
168impl<T: Clone + Signed> Complex<T> {
169 #[inline]
173 pub fn l1_norm(&self) -> T {
174 self.re.abs() + self.im.abs()
175 }
176}
177
178#[cfg(feature = "std")]
179impl<T: Clone + Float> Complex<T> {
180 #[inline]
182 pub fn norm(&self) -> T {
183 self.re.hypot(self.im)
184 }
185 #[inline]
187 pub fn arg(&self) -> T {
188 self.im.atan2(self.re)
189 }
190 #[inline]
193 pub fn to_polar(&self) -> (T, T) {
194 (self.norm(), self.arg())
195 }
196 #[inline]
198 pub fn from_polar(r: &T, theta: &T) -> Self {
199 Self::new(*r * theta.cos(), *r * theta.sin())
200 }
201
202 #[inline]
204 pub fn exp(&self) -> Self {
205 Self::from_polar(&self.re.exp(), &self.im)
208 }
209
210 #[inline]
218 pub fn ln(&self) -> Self {
219 let (r, theta) = self.to_polar();
221 Self::new(r.ln(), theta)
222 }
223
224 #[inline]
232 pub fn sqrt(&self) -> Self {
233 if self.im.is_zero() {
234 if self.re.is_sign_positive() {
235 Self::new(self.re.sqrt(), self.im)
237 } else {
238 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 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 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 #[inline]
280 pub fn cbrt(&self) -> Self {
281 if self.im.is_zero() {
282 if self.re.is_sign_positive() {
283 Self::new(self.re.cbrt(), self.im)
285 } else {
286 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 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 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 #[inline]
323 pub fn powf(&self, exp: T) -> Self {
324 let (r, theta) = self.to_polar();
327 Self::from_polar(&r.powf(exp), &(theta * exp))
328 }
329
330 #[inline]
332 pub fn log(&self, base: T) -> Self {
333 let (r, theta) = self.to_polar();
337 Self::new(r.log(base), theta / base.ln())
338 }
339
340 #[inline]
342 pub fn powc(&self, exp: Self) -> Self {
343 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 #[inline]
363 pub fn expf(&self, base: T) -> Self {
364 Self::from_polar(&base.powf(self.re), &(self.im * base.ln()))
367 }
368
369 #[inline]
371 pub fn sin(&self) -> Self {
372 Self::new(
374 self.re.sin() * self.im.cosh(),
375 self.re.cos() * self.im.sinh(),
376 )
377 }
378
379 #[inline]
381 pub fn cos(&self) -> Self {
382 Self::new(
384 self.re.cos() * self.im.cosh(),
385 -self.re.sin() * self.im.sinh(),
386 )
387 }
388
389 #[inline]
391 pub fn tan(&self) -> Self {
392 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 #[inline]
406 pub fn asin(&self) -> Self {
407 let i = Self::i();
409 -i * ((Self::one() - self * self).sqrt() + i * self).ln()
410 }
411
412 #[inline]
421 pub fn acos(&self) -> Self {
422 let i = Self::i();
424 -i * (i * (Self::one() - self * self).sqrt() + self).ln()
425 }
426
427 #[inline]
436 pub fn atan(&self) -> Self {
437 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 #[inline]
451 pub fn sinh(&self) -> Self {
452 Self::new(
454 self.re.sinh() * self.im.cos(),
455 self.re.cosh() * self.im.sin(),
456 )
457 }
458
459 #[inline]
461 pub fn cosh(&self) -> Self {
462 Self::new(
464 self.re.cosh() * self.im.cos(),
465 self.re.sinh() * self.im.sin(),
466 )
467 }
468
469 #[inline]
471 pub fn tanh(&self) -> Self {
472 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 #[inline]
486 pub fn asinh(&self) -> Self {
487 let one = Self::one();
489 (self + (one + self * self).sqrt()).ln()
490 }
491
492 #[inline]
500 pub fn acosh(&self) -> Self {
501 let one = Self::one();
503 let two = one + one;
504 two * (((self + one) / two).sqrt() + ((self - one) / two).sqrt()).ln()
505 }
506
507 #[inline]
516 pub fn atanh(&self) -> Self {
517 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 #[inline]
551 pub fn finv(&self) -> Complex<T> {
552 let norm = self.norm();
553 self.conj() / norm / norm
554 }
555
556 #[inline]
580 pub fn fdiv(&self, other: Complex<T>) -> Complex<T> {
581 self * other.finv()
582 }
583}
584
585impl<T: Clone + FloatCore> Complex<T> {
586 #[inline]
588 pub fn is_nan(self) -> bool {
589 self.re.is_nan() || self.im.is_nan()
590 }
591
592 #[inline]
594 pub fn is_infinite(self) -> bool {
595 !self.is_nan() && (self.re.is_infinite() || self.im.is_infinite())
596 }
597
598 #[inline]
600 pub fn is_finite(self) -> bool {
601 self.re.is_finite() && self.im.is_finite()
602 }
603
604 #[inline]
606 pub fn is_normal(self) -> bool {
607 self.re.is_normal() && self.im.is_normal()
608 }
609}
610
611impl<T: Clone + Num> From<T> for Complex<T> {
612 #[inline]
613 fn from(re: T) -> Self {
614 Self::new(re, T::zero())
615 }
616}
617
618impl<'a, T: Clone + Num> From<&'a T> for Complex<T> {
619 #[inline]
620 fn from(re: &T) -> Self {
621 From::from(re.clone())
622 }
623}
624
625macro_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
638macro_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
651macro_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
664macro_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
672forward_all_binop!(impl Add, add);
674
675impl<T: Clone + Num> Add<Complex<T>> for Complex<T> {
677 type Output = Self;
678
679 #[inline]
680 fn add(self, other: Self) -> Self::Output {
681 Self::Output::new(self.re + other.re, self.im + other.im)
682 }
683}
684
685forward_all_binop!(impl Sub, sub);
686
687impl<T: Clone + Num> Sub<Complex<T>> for Complex<T> {
689 type Output = Self;
690
691 #[inline]
692 fn sub(self, other: Self) -> Self::Output {
693 Self::Output::new(self.re - other.re, self.im - other.im)
694 }
695}
696
697forward_all_binop!(impl Mul, mul);
698
699impl<T: Clone + Num> Mul<Complex<T>> for Complex<T> {
701 type Output = Self;
702
703 #[inline]
704 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
711impl<T: Clone + Num + MulAdd<Output = T>> MulAdd<Complex<T>> for Complex<T> {
713 type Output = Complex<T>;
714
715 #[inline]
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()); let im = self.re.mul_add(other.im, self.im.mul_add(other.re, add.im));
720 Complex::new(re, im)
721 }
722}
723impl<'a, 'b, T: Clone + Num + MulAdd<Output = T>> MulAdd<&'b Complex<T>> for &'a Complex<T> {
724 type Output = Complex<T>;
725
726 #[inline]
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
732forward_all_binop!(impl Div, div);
733
734impl<T: Clone + Num> Div<Complex<T>> for Complex<T> {
737 type Output = Self;
738
739 #[inline]
740 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
748forward_all_binop!(impl Rem, rem);
749
750impl<T: Clone + Num> Rem<Complex<T>> for Complex<T> {
753 type Output = Self;
754
755 #[inline]
756 fn rem(self, modulus: Self) -> Self::Output {
757 let Complex { re, im } = self.clone() / modulus.clone();
758 let (re0, im0) = (re.clone() - re % T::one(), im.clone() - im % T::one());
761 self - modulus * Self::Output::new(re0, im0)
762 }
763}
764
765mod 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> {
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> {
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> {
789 fn mul_assign(&mut self, other: Self) {
790 *self = self.clone() * other;
791 }
792 }
793
794 impl<T: Clone + NumAssign + MulAddAssign> MulAddAssign for 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); self.re -= self.im.clone() * other.im.clone(); let mut adf = a;
803 adf.mul_add_assign(other.im, add.im); self.im.mul_add_assign(other.re, adf); }
806 }
807
808 impl<'a, 'b, T: Clone + NumAssign + MulAddAssign> MulAddAssign<&'a Complex<T>, &'b Complex<T>>
809 for Complex<T>
810 {
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> {
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> {
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> {
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> {
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> {
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> {
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> {
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]
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]
890 fn rem_assign(&mut self, other: &T) {
891 self.rem_assign(other.clone())
892 }
893 }
894}
895
896impl<T: Clone + Num + Neg<Output = T>> Neg for Complex<T> {
897 type Output = Self;
898
899 #[inline]
900 fn neg(self) -> Self::Output {
901 Self::Output::new(-self.re, -self.im)
902 }
903}
904
905impl<'a, T: Clone + Num + Neg<Output = T>> Neg for &'a Complex<T> {
906 type Output = Complex<T>;
907
908 #[inline]
909 fn neg(self) -> Self::Output {
910 -self.clone()
911 }
912}
913
914impl<T: Clone + Num + Neg<Output = T>> Inv for Complex<T> {
915 type Output = Self;
916
917 #[inline]
918 fn inv(self) -> Self::Output {
919 (&self).inv()
920 }
921}
922
923impl<'a, T: Clone + Num + Neg<Output = T>> Inv for &'a Complex<T> {
924 type Output = Complex<T>;
925
926 #[inline]
927 fn inv(self) -> Self::Output {
928 self.inv()
929 }
930}
931
932macro_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 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
1044impl<T: Clone + Num> Add<T> for Complex<T> {
1045 type Output = Complex<T>;
1046
1047 #[inline]
1048 fn add(self, other: T) -> Self::Output {
1049 Self::Output::new(self.re + other, self.im)
1050 }
1051}
1052
1053impl<T: Clone + Num> Sub<T> for Complex<T> {
1054 type Output = Complex<T>;
1055
1056 #[inline]
1057 fn sub(self, other: T) -> Self::Output {
1058 Self::Output::new(self.re - other, self.im)
1059 }
1060}
1061
1062impl<T: Clone + Num> Mul<T> for Complex<T> {
1063 type Output = Complex<T>;
1064
1065 #[inline]
1066 fn mul(self, other: T) -> Self::Output {
1067 Self::Output::new(self.re * other.clone(), self.im * other)
1068 }
1069}
1070
1071impl<T: Clone + Num> Div<T> for Complex<T> {
1072 type Output = Self;
1073
1074 #[inline]
1075 fn div(self, other: T) -> Self::Output {
1076 Self::Output::new(self.re / other.clone(), self.im / other)
1077 }
1078}
1079
1080impl<T: Clone + Num> Rem<T> for Complex<T> {
1081 type Output = Complex<T>;
1082
1083 #[inline]
1084 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))]
1090real_arithmetic!(usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64);
1091#[cfg(has_i128)]
1092real_arithmetic!(usize, u8, u16, u32, u64, u128, isize, i8, i16, i32, i64, i128, f32, f64);
1093
1094impl<T: Clone + Num> Zero for Complex<T> {
1096 #[inline]
1097 fn zero() -> Self {
1098 Self::new(Zero::zero(), Zero::zero())
1099 }
1100
1101 #[inline]
1102 fn is_zero(&self) -> bool {
1103 self.re.is_zero() && self.im.is_zero()
1104 }
1105
1106 #[inline]
1107 fn set_zero(&mut self) {
1108 self.re.set_zero();
1109 self.im.set_zero();
1110 }
1111}
1112
1113impl<T: Clone + Num> One for Complex<T> {
1114 #[inline]
1115 fn one() -> Self {
1116 Self::new(One::one(), Zero::zero())
1117 }
1118
1119 #[inline]
1120 fn is_one(&self) -> bool {
1121 self.re.is_one() && self.im.is_zero()
1122 }
1123
1124 #[inline]
1125 fn set_one(&mut self) {
1126 self.re.set_one();
1127 self.im.set_zero();
1128 }
1129}
1130
1131macro_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 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
1221impl<T> fmt::Display for Complex<T>
1223where
1224 T: fmt::Display + Num + PartialOrd + Clone,
1225{
1226 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1227 write_complex!(f, "", "", self.re, self.im, T)
1228 }
1229}
1230
1231impl<T> fmt::LowerExp for Complex<T>
1232where
1233 T: fmt::LowerExp + Num + PartialOrd + Clone,
1234{
1235 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1236 write_complex!(f, "e", "", self.re, self.im, T)
1237 }
1238}
1239
1240impl<T> fmt::UpperExp for Complex<T>
1241where
1242 T: fmt::UpperExp + Num + PartialOrd + Clone,
1243{
1244 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1245 write_complex!(f, "E", "", self.re, self.im, T)
1246 }
1247}
1248
1249impl<T> fmt::LowerHex for Complex<T>
1250where
1251 T: fmt::LowerHex + Num + PartialOrd + Clone,
1252{
1253 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1254 write_complex!(f, "x", "0x", self.re, self.im, T)
1255 }
1256}
1257
1258impl<T> fmt::UpperHex for Complex<T>
1259where
1260 T: fmt::UpperHex + Num + PartialOrd + Clone,
1261{
1262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1263 write_complex!(f, "X", "0x", self.re, self.im, T)
1264 }
1265}
1266
1267impl<T> fmt::Octal for Complex<T>
1268where
1269 T: fmt::Octal + Num + PartialOrd + Clone,
1270{
1271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1272 write_complex!(f, "o", "0o", self.re, self.im, T)
1273 }
1274}
1275
1276impl<T> fmt::Binary for Complex<T>
1277where
1278 T: fmt::Binary + Num + PartialOrd + Clone,
1279{
1280 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)] fn from_str_generic<T, E, F>(s: &str, from: F) -> Result<Complex<T>, ParseComplexError<E>>
1287where
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 if (c == b'+' || c == b'-') && !(p == b'e' || p == b'E') {
1325 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 if b.is_empty() {
1339 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 let re = try!(from(re).map_err(ParseComplexError::from_error));
1366 let re = if neg_re { T::zero() - re } else { re };
1367
1368 let mut im = &im[..im.len() - 1];
1370 if im.is_empty() || im == "+" {
1372 im = "1";
1373 } else if im == "-" {
1374 im = "-1";
1375 }
1376
1377 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
1384impl<T> FromStr for Complex<T>
1385where
1386 T: FromStr + Num + Clone,
1387{
1388 type Err = ParseComplexError<T::Err>;
1389
1390 fn from_str(s: &str) -> Result<Self, Self::Err> {
1392 from_str_generic(s, T::from_str)
1393 }
1394}
1395
1396impl<T: Num + Clone> Num for Complex<T> {
1397 type FromStrRadixErr = ParseComplexError<T::FromStrRadixErr>;
1398
1399 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
1407impl<T: Num + Clone> Sum for Complex<T> {
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
1416impl<'a, T: 'a + Num + Clone> Sum<&'a Complex<T>> for 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
1425impl<T: Num + Clone> Product for Complex<T> {
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
1434impl<'a, T: 'a + Num + Clone> Product<&'a Complex<T>> for 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")]
1444impl<T> serde::Serialize for Complex<T>
1445where
1446 T: serde::Serialize,
1447{
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")]
1457impl<'de, T> serde::Deserialize<'de> for Complex<T>
1458where
1459 T: serde::Deserialize<'de> + Num + Clone,
1460{
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)]
1471pub struct ParseComplexError<E> {
1472 kind: ComplexErrorKind<E>,
1473}
1474
1475#[derive(Debug, PartialEq)]
1476enum ComplexErrorKind<E> {
1477 ParseError(E),
1478 ExprError,
1479}
1480
1481impl<E> ParseComplexError<E> {
1482 fn new() -> Self {
1483 ParseComplexError {
1484 kind: ComplexErrorKind::ExprError,
1485 }
1486 }
1487
1488 fn from_error(error: E) -> Self {
1489 ParseComplexError {
1490 kind: ComplexErrorKind::ParseError(error),
1491 }
1492 }
1493}
1494
1495#[cfg(feature = "std")]
1496impl<E: Error> Error for ParseComplexError<E> {
1497 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
1505impl<E: fmt::Display> fmt::Display for ParseComplexError<E> {
1506 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)]
1515fn 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)]
1524mod 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]
1545 fn test_consts() {
1546 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]
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]
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]
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]
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]
1592 fn test_inv_zero() {
1593 assert!(_0_0i.inv().is_nan());
1595 }
1596
1597 #[test]
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]
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 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]
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]
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
1669 fn close(a: Complex64, b: Complex64) -> bool {
1670 close_to_tol(a, b, 1e-10)
1671 }
1672
1673 fn close_to_tol(a: Complex64, b: Complex64, tol: f64) -> bool {
1674 let close = (a == b) || (a - b).norm() < tol;
1676 if !close {
1677 println!("{:?} != {:?}", a, b);
1678 }
1679 close
1680 }
1681
1682 #[test]
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 assert!(close(c.conj().exp(), c.exp().conj()));
1695 assert!(close(
1697 c.exp(),
1698 (c + _0_1i.scale(f64::consts::PI * 2.0)).exp()
1699 ));
1700 }
1701 }
1702
1703 #[test]
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 assert!(close(c.conj().ln(), c.ln().conj()));
1715 assert!(-f64::consts::PI <= c.ln().arg() && c.ln().arg() <= f64::consts::PI);
1717 }
1718 }
1719
1720 #[test]
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]
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]
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]
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]
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 assert!(close(c.conj().sqrt(), c.sqrt().conj()));
1775 assert!(
1777 -f64::consts::FRAC_PI_2 <= c.sqrt().arg()
1778 && c.sqrt().arg() <= f64::consts::FRAC_PI_2
1779 );
1780 assert!(close(c.sqrt() * c.sqrt(), c));
1782 }
1783 }
1784
1785 #[test]
1786 fn test_sqrt_real() {
1787 for n in (0..100).map(f64::from) {
1788 let n2 = n * n;
1790 assert_eq!(Complex64::new(n2, 0.0).sqrt(), Complex64::new(n, 0.0));
1791 assert_eq!(Complex64::new(-n2, 0.0).sqrt(), Complex64::new(0.0, n));
1793 assert_eq!(Complex64::new(-n2, -0.0).sqrt(), Complex64::new(0.0, -n));
1795 }
1796 }
1797
1798 #[test]
1799 fn test_sqrt_imag() {
1800 for n in (0..100).map(f64::from) {
1801 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 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]
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 assert!(close(c.conj().cbrt(), c.cbrt().conj()));
1832 assert!(
1834 -f64::consts::FRAC_PI_3 <= c.cbrt().arg()
1835 && c.cbrt().arg() <= f64::consts::FRAC_PI_3
1836 );
1837 assert!(close(c.cbrt() * c.cbrt() * c.cbrt(), c));
1839 }
1840 }
1841
1842 #[test]
1843 fn test_cbrt_real() {
1844 for n in (0..100).map(f64::from) {
1845 let n3 = n * n * n;
1847 assert!(close(
1848 Complex64::new(n3, 0.0).cbrt(),
1849 Complex64::new(n, 0.0)
1850 ));
1851 assert!(close(
1853 Complex64::new(-n3, 0.0).cbrt(),
1854 Complex64::from_polar(&n, &(f64::consts::FRAC_PI_3))
1855 ));
1856 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]
1865 fn test_cbrt_imag() {
1866 for n in (0..100).map(f64::from) {
1867 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 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]
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 assert!(close(c.conj().sin(), c.sin().conj()));
1889 assert!(close(c.scale(-1.0).sin(), c.sin().scale(-1.0)));
1891 }
1892 }
1893
1894 #[test]
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 assert!(close(c.conj().cos(), c.cos().conj()));
1902 assert!(close(c.scale(-1.0).cos(), c.cos()));
1904 }
1905 }
1906
1907 #[test]
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 assert!(close(c.conj().tan(), c.tan().conj()));
1915 assert!(close(c.scale(-1.0).tan(), c.tan().scale(-1.0)));
1917 }
1918 }
1919
1920 #[test]
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 assert!(close(c.conj().asin(), c.asin().conj()));
1932 assert!(close(c.scale(-1.0).asin(), c.asin().scale(-1.0)));
1934 assert!(
1936 -f64::consts::PI / 2.0 <= c.asin().re && c.asin().re <= f64::consts::PI / 2.0
1937 );
1938 }
1939 }
1940
1941 #[test]
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 assert!(close(c.conj().acos(), c.acos().conj()));
1956 assert!(0.0 <= c.acos().re && c.acos().re <= f64::consts::PI);
1958 }
1959 }
1960
1961 #[test]
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 assert!(close(c.conj().atan(), c.atan().conj()));
1973 assert!(close(c.scale(-1.0).atan(), c.atan().scale(-1.0)));
1975 assert!(
1977 -f64::consts::PI / 2.0 <= c.atan().re && c.atan().re <= f64::consts::PI / 2.0
1978 );
1979 }
1980 }
1981
1982 #[test]
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 assert!(close(c.conj().sinh(), c.sinh().conj()));
1993 assert!(close(c.scale(-1.0).sinh(), c.sinh().scale(-1.0)));
1995 }
1996 }
1997
1998 #[test]
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 assert!(close(c.conj().cosh(), c.cosh().conj()));
2009 assert!(close(c.scale(-1.0).cosh(), c.cosh()));
2011 }
2012 }
2013
2014 #[test]
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 assert!(close(c.conj().tanh(), c.conj().tanh()));
2025 assert!(close(c.scale(-1.0).tanh(), c.tanh().scale(-1.0)));
2027 }
2028 }
2029
2030 #[test]
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 assert!(close(c.conj().asinh(), c.conj().asinh()));
2042 assert!(close(c.scale(-1.0).asinh(), c.asinh().scale(-1.0)));
2044 assert!(
2046 -f64::consts::PI / 2.0 <= c.asinh().im && c.asinh().im <= f64::consts::PI / 2.0
2047 );
2048 }
2049 }
2050
2051 #[test]
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 assert!(close(c.conj().acosh(), c.conj().acosh()));
2062 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]
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 assert!(close(c.conj().atanh(), c.conj().atanh()));
2079 assert!(close(c.scale(-1.0).atanh(), c.atanh().scale(-1.0)));
2081 assert!(
2083 -f64::consts::PI / 2.0 <= c.atanh().im && c.atanh().im <= f64::consts::PI / 2.0
2084 );
2085 }
2086 }
2087
2088 #[test]
2089 fn test_exp_ln() {
2090 for &c in all_consts.iter() {
2091 assert!(close(c.ln().exp(), c));
2093 }
2094 }
2095
2096 #[test]
2097 fn test_trig_to_hyperbolic() {
2098 for &c in all_consts.iter() {
2099 assert!(close((_0_1i * c).sin(), _0_1i * c.sinh()));
2101 assert!(close((_0_1i * c).cos(), c.cosh()));
2103 assert!(close((_0_1i * c).tan(), _0_1i * c.tanh()));
2105 }
2106 }
2107
2108 #[test]
2109 fn test_trig_identities() {
2110 for &c in all_consts.iter() {
2111 assert!(close(c.tan(), c.sin() / c.cos()));
2113 assert!(close(c.sin() * c.sin() + c.cos() * c.cos(), _1_0i));
2115
2116 assert!(close(c.asin().sin(), c));
2118 assert!(close(c.acos().cos(), c));
2120 if c != _0_1i && c != _0_1i.scale(-1.0) {
2123 assert!(close(c.atan().tan(), c));
2124 }
2125
2126 assert!(close(
2128 ((_0_1i * c).exp() - (_0_1i * c).exp().inv()) / _0_1i.scale(2.0),
2129 c.sin()
2130 ));
2131 assert!(close(
2133 ((_0_1i * c).exp() + (_0_1i * c).exp().inv()).unscale(2.0),
2134 c.cos()
2135 ));
2136 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]
2146 fn test_hyperbolic_identites() {
2147 for &c in all_consts.iter() {
2148 assert!(close(c.tanh(), c.sinh() / c.cosh()));
2150 assert!(close(c.cosh() * c.cosh() - c.sinh() * c.sinh(), _1_0i));
2152
2153 assert!(close(c.asinh().sinh(), c));
2155 assert!(close(c.acosh().cosh(), c));
2157 if c != _1_0i && c != _1_0i.scale(-1.0) {
2160 assert!(close(c.atanh().tanh(), c));
2161 }
2162
2163 assert!(close((c.exp() - c.exp().inv()).unscale(2.0), c.sinh()));
2165 assert!(close((c.exp() + c.exp().inv()).unscale(2.0), c.cosh()));
2167 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 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 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]
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]
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]
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 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")]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
2413 fn test_div_rem_gaussian() {
2414 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]
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]
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]
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]
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]
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]
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]
2499 fn test_is_infinite() {
2500 let a = Complex::new(2f64, f64::INFINITY);
2501 assert!(a.is_infinite());
2502 }
2503
2504 #[test]
2505 fn test_is_finite() {
2506 assert!(_1_1i.is_finite())
2507 }
2508
2509 #[test]
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]
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]
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]
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]
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]
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]
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]
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]
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}