complex.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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. //! Complex numbers.
  11. use std::fmt;
  12. use std::ops::{Add, Div, Mul, Neg, Sub};
  13. use {Zero, One, Num, Float};
  14. // FIXME #1284: handle complex NaN & infinity etc. This
  15. // probably doesn't map to C's _Complex correctly.
  16. /// A complex number in Cartesian form.
  17. #[derive(PartialEq, Copy, Clone, Hash, Debug)]
  18. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  19. pub struct Complex<T> {
  20. /// Real portion of the complex number
  21. pub re: T,
  22. /// Imaginary portion of the complex number
  23. pub im: T
  24. }
  25. pub type Complex32 = Complex<f32>;
  26. pub type Complex64 = Complex<f64>;
  27. impl<T: Clone + Num> Complex<T> {
  28. /// Create a new Complex
  29. #[inline]
  30. pub fn new(re: T, im: T) -> Complex<T> {
  31. Complex { re: re, im: im }
  32. }
  33. /// Returns the square of the norm (since `T` doesn't necessarily
  34. /// have a sqrt function), i.e. `re^2 + im^2`.
  35. #[inline]
  36. pub fn norm_sqr(&self) -> T {
  37. self.re.clone() * self.re.clone() + self.im.clone() * self.im.clone()
  38. }
  39. /// Multiplies `self` by the scalar `t`.
  40. #[inline]
  41. pub fn scale(&self, t: T) -> Complex<T> {
  42. Complex::new(self.re.clone() * t.clone(), self.im.clone() * t)
  43. }
  44. /// Divides `self` by the scalar `t`.
  45. #[inline]
  46. pub fn unscale(&self, t: T) -> Complex<T> {
  47. Complex::new(self.re.clone() / t.clone(), self.im.clone() / t)
  48. }
  49. }
  50. impl<T: Clone + Num + Neg<Output = T>> Complex<T> {
  51. /// Returns the complex conjugate. i.e. `re - i im`
  52. #[inline]
  53. pub fn conj(&self) -> Complex<T> {
  54. Complex::new(self.re.clone(), -self.im.clone())
  55. }
  56. /// Returns `1/self`
  57. #[inline]
  58. pub fn inv(&self) -> Complex<T> {
  59. let norm_sqr = self.norm_sqr();
  60. Complex::new(self.re.clone() / norm_sqr.clone(),
  61. -self.im.clone() / norm_sqr)
  62. }
  63. }
  64. impl<T: Clone + Float> Complex<T> {
  65. /// Calculate |self|
  66. #[inline]
  67. pub fn norm(&self) -> T {
  68. self.re.clone().hypot(self.im.clone())
  69. }
  70. /// Calculate the principal Arg of self.
  71. #[inline]
  72. pub fn arg(&self) -> T {
  73. self.im.clone().atan2(self.re.clone())
  74. }
  75. /// Convert to polar form (r, theta), such that `self = r * exp(i
  76. /// * theta)`
  77. #[inline]
  78. pub fn to_polar(&self) -> (T, T) {
  79. (self.norm(), self.arg())
  80. }
  81. /// Convert a polar representation into a complex number.
  82. #[inline]
  83. pub fn from_polar(r: &T, theta: &T) -> Complex<T> {
  84. Complex::new(*r * theta.cos(), *r * theta.sin())
  85. }
  86. /// Computes `e^(self)`, where `e` is the base of the natural logarithm.
  87. #[inline]
  88. pub fn exp(&self) -> Complex<T> {
  89. // formula: e^(a + bi) = e^a (cos(b) + i*sin(b))
  90. Complex::new(self.im.clone().cos(), self.im.clone().sin()).scale(self.re.clone().exp())
  91. }
  92. /// Computes the principal value of natural logarithm of `self`.
  93. ///
  94. /// This function has one branch cut:
  95. ///
  96. /// * `(-∞, 0]`, continuous from above.
  97. ///
  98. /// The branch satisfies `-π ≤ arg(ln(z)) ≤ π`.
  99. #[inline]
  100. pub fn ln(&self) -> Complex<T> {
  101. // formula: ln(z) = ln|z| + i*arg(z)
  102. Complex::new(self.norm().ln(), self.arg())
  103. }
  104. /// Computes the principal value of the square root of `self`.
  105. ///
  106. /// This function has one branch cut:
  107. ///
  108. /// * `(-∞, 0)`, continuous from above.
  109. ///
  110. /// The branch satisfies `-π/2 ≤ arg(sqrt(z)) ≤ π/2`.
  111. #[inline]
  112. pub fn sqrt(&self) -> Complex<T> {
  113. // formula: sqrt(r e^(it)) = sqrt(r) e^(it/2)
  114. let two = T::one() + T::one();
  115. let (r, theta) = self.to_polar();
  116. Complex::from_polar(&(r.sqrt()), &(theta/two))
  117. }
  118. /// Computes the sine of `self`.
  119. #[inline]
  120. pub fn sin(&self) -> Complex<T> {
  121. // formula: sin(a + bi) = sin(a)cosh(b) + i*cos(a)sinh(b)
  122. Complex::new(self.re.clone().sin() * self.im.clone().cosh(), self.re.clone().cos() * self.im.clone().sinh())
  123. }
  124. /// Computes the cosine of `self`.
  125. #[inline]
  126. pub fn cos(&self) -> Complex<T> {
  127. // formula: cos(a + bi) = cos(a)cosh(b) - i*sin(a)sinh(b)
  128. Complex::new(self.re.clone().cos() * self.im.clone().cosh(), -self.re.clone().sin() * self.im.clone().sinh())
  129. }
  130. /// Computes the tangent of `self`.
  131. #[inline]
  132. pub fn tan(&self) -> Complex<T> {
  133. // formula: tan(a + bi) = (sin(2a) + i*sinh(2b))/(cos(2a) + cosh(2b))
  134. let (two_re, two_im) = (self.re.clone() + self.re.clone(), self.im.clone() + self.im.clone());
  135. Complex::new(two_re.clone().sin(), two_im.clone().sinh()).unscale(two_re.cos() + two_im.cosh())
  136. }
  137. /// Computes the principal value of the inverse sine of `self`.
  138. ///
  139. /// This function has two branch cuts:
  140. ///
  141. /// * `(-∞, -1)`, continuous from above.
  142. /// * `(1, ∞)`, continuous from below.
  143. ///
  144. /// The branch satisfies `-π/2 ≤ Re(asin(z)) ≤ π/2`.
  145. #[inline]
  146. pub fn asin(&self) -> Complex<T> {
  147. // formula: arcsin(z) = -i ln(sqrt(1-z^2) + iz)
  148. let i = Complex::new(T::zero(), T::one());
  149. -i*((Complex::one() - self*self).sqrt() + i*self).ln()
  150. }
  151. /// Computes the principal value of the inverse cosine of `self`.
  152. ///
  153. /// This function has two branch cuts:
  154. ///
  155. /// * `(-∞, -1)`, continuous from above.
  156. /// * `(1, ∞)`, continuous from below.
  157. ///
  158. /// The branch satisfies `0 ≤ Re(acos(z)) ≤ π`.
  159. #[inline]
  160. pub fn acos(&self) -> Complex<T> {
  161. // formula: arccos(z) = -i ln(i sqrt(1-z^2) + z)
  162. let i = Complex::new(T::zero(), T::one());
  163. -i*(i*(Complex::one() - self*self).sqrt() + self).ln()
  164. }
  165. /// Computes the principal value of the inverse tangent of `self`.
  166. ///
  167. /// This function has two branch cuts:
  168. ///
  169. /// * `(-∞i, -i]`, continuous from the left.
  170. /// * `[i, ∞i)`, continuous from the right.
  171. ///
  172. /// The branch satisfies `-π/2 ≤ Re(atan(z)) ≤ π/2`.
  173. #[inline]
  174. pub fn atan(&self) -> Complex<T> {
  175. // formula: arctan(z) = (ln(1+iz) - ln(1-iz))/(2i)
  176. let i = Complex::new(T::zero(), T::one());
  177. let one = Complex::one();
  178. let two = one + one;
  179. if *self == i {
  180. return Complex::new(T::zero(), T::infinity());
  181. }
  182. else if *self == -i {
  183. return Complex::new(T::zero(), -T::infinity());
  184. }
  185. ((one + i * self).ln() - (one - i * self).ln()) / (two * i)
  186. }
  187. /// Computes the hyperbolic sine of `self`.
  188. #[inline]
  189. pub fn sinh(&self) -> Complex<T> {
  190. // formula: sinh(a + bi) = sinh(a)cos(b) + i*cosh(a)sin(b)
  191. Complex::new(self.re.clone().sinh() * self.im.clone().cos(), self.re.clone().cosh() * self.im.clone().sin())
  192. }
  193. /// Computes the hyperbolic cosine of `self`.
  194. #[inline]
  195. pub fn cosh(&self) -> Complex<T> {
  196. // formula: cosh(a + bi) = cosh(a)cos(b) + i*sinh(a)sin(b)
  197. Complex::new(self.re.clone().cosh() * self.im.clone().cos(), self.re.clone().sinh() * self.im.clone().sin())
  198. }
  199. /// Computes the hyperbolic tangent of `self`.
  200. #[inline]
  201. pub fn tanh(&self) -> Complex<T> {
  202. // formula: tanh(a + bi) = (sinh(2a) + i*sin(2b))/(cosh(2a) + cos(2b))
  203. let (two_re, two_im) = (self.re.clone() + self.re.clone(), self.im.clone() + self.im.clone());
  204. Complex::new(two_re.clone().sinh(), two_im.clone().sin()).unscale(two_re.cosh() + two_im.cos())
  205. }
  206. /// Computes the principal value of inverse hyperbolic sine of `self`.
  207. ///
  208. /// This function has two branch cuts:
  209. ///
  210. /// * `(-∞i, -i)`, continuous from the left.
  211. /// * `(i, ∞i)`, continuous from the right.
  212. ///
  213. /// The branch satisfies `-π/2 ≤ Im(asinh(z)) ≤ π/2`.
  214. #[inline]
  215. pub fn asinh(&self) -> Complex<T> {
  216. // formula: arcsinh(z) = ln(z + sqrt(1+z^2))
  217. let one = Complex::one();
  218. (self + (one + self * self).sqrt()).ln()
  219. }
  220. /// Computes the principal value of inverse hyperbolic cosine of `self`.
  221. ///
  222. /// This function has one branch cut:
  223. ///
  224. /// * `(-∞, 1)`, continuous from above.
  225. ///
  226. /// The branch satisfies `-π ≤ Im(acosh(z)) ≤ π` and `0 ≤ Re(acosh(z)) < ∞`.
  227. #[inline]
  228. pub fn acosh(&self) -> Complex<T> {
  229. // formula: arccosh(z) = 2 ln(sqrt((z+1)/2) + sqrt((z-1)/2))
  230. let one = Complex::one();
  231. let two = one + one;
  232. two * (((self + one)/two).sqrt() + ((self - one)/two).sqrt()).ln()
  233. }
  234. /// Computes the principal value of inverse hyperbolic tangent of `self`.
  235. ///
  236. /// This function has two branch cuts:
  237. ///
  238. /// * `(-∞, -1]`, continuous from above.
  239. /// * `[1, ∞)`, continuous from below.
  240. ///
  241. /// The branch satisfies `-π/2 ≤ Im(atanh(z)) ≤ π/2`.
  242. #[inline]
  243. pub fn atanh(&self) -> Complex<T> {
  244. // formula: arctanh(z) = (ln(1+z) - ln(1-z))/2
  245. let one = Complex::one();
  246. let two = one + one;
  247. if *self == one {
  248. return Complex::new(T::infinity(), T::zero());
  249. }
  250. else if *self == -one {
  251. return Complex::new(-T::infinity(), T::zero());
  252. }
  253. ((one + self).ln() - (one - self).ln()) / two
  254. }
  255. }
  256. macro_rules! forward_val_val_binop {
  257. (impl $imp:ident, $method:ident) => {
  258. impl<T: Clone + Num> $imp<Complex<T>> for Complex<T> {
  259. type Output = Complex<T>;
  260. #[inline]
  261. fn $method(self, other: Complex<T>) -> Complex<T> {
  262. (&self).$method(&other)
  263. }
  264. }
  265. }
  266. }
  267. macro_rules! forward_ref_val_binop {
  268. (impl $imp:ident, $method:ident) => {
  269. impl<'a, T: Clone + Num> $imp<Complex<T>> for &'a Complex<T> {
  270. type Output = Complex<T>;
  271. #[inline]
  272. fn $method(self, other: Complex<T>) -> Complex<T> {
  273. self.$method(&other)
  274. }
  275. }
  276. }
  277. }
  278. macro_rules! forward_val_ref_binop {
  279. (impl $imp:ident, $method:ident) => {
  280. impl<'a, T: Clone + Num> $imp<&'a Complex<T>> for Complex<T> {
  281. type Output = Complex<T>;
  282. #[inline]
  283. fn $method(self, other: &Complex<T>) -> Complex<T> {
  284. (&self).$method(other)
  285. }
  286. }
  287. }
  288. }
  289. macro_rules! forward_all_binop {
  290. (impl $imp:ident, $method:ident) => {
  291. forward_val_val_binop!(impl $imp, $method);
  292. forward_ref_val_binop!(impl $imp, $method);
  293. forward_val_ref_binop!(impl $imp, $method);
  294. };
  295. }
  296. /* arithmetic */
  297. forward_all_binop!(impl Add, add);
  298. // (a + i b) + (c + i d) == (a + c) + i (b + d)
  299. impl<'a, 'b, T: Clone + Num> Add<&'b Complex<T>> for &'a Complex<T> {
  300. type Output = Complex<T>;
  301. #[inline]
  302. fn add(self, other: &Complex<T>) -> Complex<T> {
  303. Complex::new(self.re.clone() + other.re.clone(),
  304. self.im.clone() + other.im.clone())
  305. }
  306. }
  307. forward_all_binop!(impl Sub, sub);
  308. // (a + i b) - (c + i d) == (a - c) + i (b - d)
  309. impl<'a, 'b, T: Clone + Num> Sub<&'b Complex<T>> for &'a Complex<T> {
  310. type Output = Complex<T>;
  311. #[inline]
  312. fn sub(self, other: &Complex<T>) -> Complex<T> {
  313. Complex::new(self.re.clone() - other.re.clone(),
  314. self.im.clone() - other.im.clone())
  315. }
  316. }
  317. forward_all_binop!(impl Mul, mul);
  318. // (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c)
  319. impl<'a, 'b, T: Clone + Num> Mul<&'b Complex<T>> for &'a Complex<T> {
  320. type Output = Complex<T>;
  321. #[inline]
  322. fn mul(self, other: &Complex<T>) -> Complex<T> {
  323. Complex::new(self.re.clone() * other.re.clone() - self.im.clone() * other.im.clone(),
  324. self.re.clone() * other.im.clone() + self.im.clone() * other.re.clone())
  325. }
  326. }
  327. forward_all_binop!(impl Div, div);
  328. // (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d)
  329. // == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)]
  330. impl<'a, 'b, T: Clone + Num> Div<&'b Complex<T>> for &'a Complex<T> {
  331. type Output = Complex<T>;
  332. #[inline]
  333. fn div(self, other: &Complex<T>) -> Complex<T> {
  334. let norm_sqr = other.norm_sqr();
  335. Complex::new((self.re.clone() * other.re.clone() + self.im.clone() * other.im.clone()) / norm_sqr.clone(),
  336. (self.im.clone() * other.re.clone() - self.re.clone() * other.im.clone()) / norm_sqr)
  337. }
  338. }
  339. impl<T: Clone + Num + Neg<Output = T>> Neg for Complex<T> {
  340. type Output = Complex<T>;
  341. #[inline]
  342. fn neg(self) -> Complex<T> { -&self }
  343. }
  344. impl<'a, T: Clone + Num + Neg<Output = T>> Neg for &'a Complex<T> {
  345. type Output = Complex<T>;
  346. #[inline]
  347. fn neg(self) -> Complex<T> {
  348. Complex::new(-self.re.clone(), -self.im.clone())
  349. }
  350. }
  351. /* constants */
  352. impl<T: Clone + Num> Zero for Complex<T> {
  353. #[inline]
  354. fn zero() -> Complex<T> {
  355. Complex::new(Zero::zero(), Zero::zero())
  356. }
  357. #[inline]
  358. fn is_zero(&self) -> bool {
  359. self.re.is_zero() && self.im.is_zero()
  360. }
  361. }
  362. impl<T: Clone + Num> One for Complex<T> {
  363. #[inline]
  364. fn one() -> Complex<T> {
  365. Complex::new(One::one(), Zero::zero())
  366. }
  367. }
  368. /* string conversions */
  369. impl<T> fmt::Display for Complex<T> where
  370. T: fmt::Display + Num + PartialOrd + Clone
  371. {
  372. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  373. if self.im < Zero::zero() {
  374. write!(f, "{}-{}i", self.re, T::zero() - self.im.clone())
  375. } else {
  376. write!(f, "{}+{}i", self.re, self.im)
  377. }
  378. }
  379. }
  380. #[cfg(test)]
  381. mod test {
  382. #![allow(non_upper_case_globals)]
  383. use super::{Complex64, Complex};
  384. use std::f64;
  385. use {Zero, One, Float};
  386. pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
  387. pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
  388. pub const _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 };
  389. pub const _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 };
  390. pub const _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 };
  391. pub const _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 };
  392. pub const all_consts : [Complex64; 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i];
  393. #[test]
  394. fn test_consts() {
  395. // check our constants are what Complex::new creates
  396. fn test(c : Complex64, r : f64, i: f64) {
  397. assert_eq!(c, Complex::new(r,i));
  398. }
  399. test(_0_0i, 0.0, 0.0);
  400. test(_1_0i, 1.0, 0.0);
  401. test(_1_1i, 1.0, 1.0);
  402. test(_neg1_1i, -1.0, 1.0);
  403. test(_05_05i, 0.5, 0.5);
  404. assert_eq!(_0_0i, Zero::zero());
  405. assert_eq!(_1_0i, One::one());
  406. }
  407. #[test]
  408. #[cfg_attr(target_arch = "x86", ignore)]
  409. // FIXME #7158: (maybe?) currently failing on x86.
  410. fn test_norm() {
  411. fn test(c: Complex64, ns: f64) {
  412. assert_eq!(c.norm_sqr(), ns);
  413. assert_eq!(c.norm(), ns.sqrt())
  414. }
  415. test(_0_0i, 0.0);
  416. test(_1_0i, 1.0);
  417. test(_1_1i, 2.0);
  418. test(_neg1_1i, 2.0);
  419. test(_05_05i, 0.5);
  420. }
  421. #[test]
  422. fn test_scale_unscale() {
  423. assert_eq!(_05_05i.scale(2.0), _1_1i);
  424. assert_eq!(_1_1i.unscale(2.0), _05_05i);
  425. for &c in all_consts.iter() {
  426. assert_eq!(c.scale(2.0).unscale(2.0), c);
  427. }
  428. }
  429. #[test]
  430. fn test_conj() {
  431. for &c in all_consts.iter() {
  432. assert_eq!(c.conj(), Complex::new(c.re, -c.im));
  433. assert_eq!(c.conj().conj(), c);
  434. }
  435. }
  436. #[test]
  437. fn test_inv() {
  438. assert_eq!(_1_1i.inv(), _05_05i.conj());
  439. assert_eq!(_1_0i.inv(), _1_0i.inv());
  440. }
  441. #[test]
  442. #[should_panic]
  443. fn test_divide_by_zero_natural() {
  444. let n = Complex::new(2, 3);
  445. let d = Complex::new(0, 0);
  446. let _x = n / d;
  447. }
  448. #[test]
  449. #[should_panic]
  450. #[ignore]
  451. fn test_inv_zero() {
  452. // FIXME #5736: should this really fail, or just NaN?
  453. _0_0i.inv();
  454. }
  455. #[test]
  456. fn test_arg() {
  457. fn test(c: Complex64, arg: f64) {
  458. assert!((c.arg() - arg).abs() < 1.0e-6)
  459. }
  460. test(_1_0i, 0.0);
  461. test(_1_1i, 0.25 * f64::consts::PI);
  462. test(_neg1_1i, 0.75 * f64::consts::PI);
  463. test(_05_05i, 0.25 * f64::consts::PI);
  464. }
  465. #[test]
  466. fn test_polar_conv() {
  467. fn test(c: Complex64) {
  468. let (r, theta) = c.to_polar();
  469. assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6);
  470. }
  471. for &c in all_consts.iter() { test(c); }
  472. }
  473. fn close(a: Complex64, b: Complex64) -> bool {
  474. // returns true if a and b are reasonably close
  475. (a == b) || (a-b).norm() < 1e-10
  476. }
  477. #[test]
  478. fn test_exp() {
  479. assert!(close(_1_0i.exp(), _1_0i.scale(f64::consts::E)));
  480. assert!(close(_0_0i.exp(), _1_0i));
  481. assert!(close(_0_1i.exp(), Complex::new(1.0.cos(), 1.0.sin())));
  482. assert!(close(_05_05i.exp()*_05_05i.exp(), _1_1i.exp()));
  483. assert!(close(_0_1i.scale(-f64::consts::PI).exp(), _1_0i.scale(-1.0)));
  484. for &c in all_consts.iter() {
  485. // e^conj(z) = conj(e^z)
  486. assert!(close(c.conj().exp(), c.exp().conj()));
  487. // e^(z + 2 pi i) = e^z
  488. assert!(close(c.exp(), (c + _0_1i.scale(f64::consts::PI*2.0)).exp()));
  489. }
  490. }
  491. #[test]
  492. fn test_ln() {
  493. assert!(close(_1_0i.ln(), _0_0i));
  494. assert!(close(_0_1i.ln(), _0_1i.scale(f64::consts::PI/2.0)));
  495. assert!(close(_0_0i.ln(), Complex::new(f64::neg_infinity(), 0.0)));
  496. assert!(close((_neg1_1i * _05_05i).ln(), _neg1_1i.ln() + _05_05i.ln()));
  497. for &c in all_consts.iter() {
  498. // ln(conj(z() = conj(ln(z))
  499. assert!(close(c.conj().ln(), c.ln().conj()));
  500. // for this branch, -pi <= arg(ln(z)) <= pi
  501. assert!(-f64::consts::PI <= c.ln().arg() && c.ln().arg() <= f64::consts::PI);
  502. }
  503. }
  504. #[test]
  505. fn test_sqrt() {
  506. assert!(close(_0_0i.sqrt(), _0_0i));
  507. assert!(close(_1_0i.sqrt(), _1_0i));
  508. assert!(close(Complex::new(-1.0, 0.0).sqrt(), _0_1i));
  509. assert!(close(Complex::new(-1.0, -0.0).sqrt(), _0_1i.scale(-1.0)));
  510. assert!(close(_0_1i.sqrt(), _05_05i.scale(2.0.sqrt())));
  511. for &c in all_consts.iter() {
  512. // sqrt(conj(z() = conj(sqrt(z))
  513. assert!(close(c.conj().sqrt(), c.sqrt().conj()));
  514. // for this branch, -pi/2 <= arg(sqrt(z)) <= pi/2
  515. assert!(-f64::consts::PI/2.0 <= c.sqrt().arg() && c.sqrt().arg() <= f64::consts::PI/2.0);
  516. // sqrt(z) * sqrt(z) = z
  517. assert!(close(c.sqrt()*c.sqrt(), c));
  518. }
  519. }
  520. #[test]
  521. fn test_sin() {
  522. assert!(close(_0_0i.sin(), _0_0i));
  523. assert!(close(_1_0i.scale(f64::consts::PI*2.0).sin(), _0_0i));
  524. assert!(close(_0_1i.sin(), _0_1i.scale(1.0.sinh())));
  525. for &c in all_consts.iter() {
  526. // sin(conj(z)) = conj(sin(z))
  527. assert!(close(c.conj().sin(), c.sin().conj()));
  528. // sin(-z) = -sin(z)
  529. assert!(close(c.scale(-1.0).sin(), c.sin().scale(-1.0)));
  530. }
  531. }
  532. #[test]
  533. fn test_cos() {
  534. assert!(close(_0_0i.cos(), _1_0i));
  535. assert!(close(_1_0i.scale(f64::consts::PI*2.0).cos(), _1_0i));
  536. assert!(close(_0_1i.cos(), _1_0i.scale(1.0.cosh())));
  537. for &c in all_consts.iter() {
  538. // cos(conj(z)) = conj(cos(z))
  539. assert!(close(c.conj().cos(), c.cos().conj()));
  540. // cos(-z) = cos(z)
  541. assert!(close(c.scale(-1.0).cos(), c.cos()));
  542. }
  543. }
  544. #[test]
  545. fn test_tan() {
  546. assert!(close(_0_0i.tan(), _0_0i));
  547. assert!(close(_1_0i.scale(f64::consts::PI/4.0).tan(), _1_0i));
  548. assert!(close(_1_0i.scale(f64::consts::PI).tan(), _0_0i));
  549. for &c in all_consts.iter() {
  550. // tan(conj(z)) = conj(tan(z))
  551. assert!(close(c.conj().tan(), c.tan().conj()));
  552. // tan(-z) = -tan(z)
  553. assert!(close(c.scale(-1.0).tan(), c.tan().scale(-1.0)));
  554. }
  555. }
  556. #[test]
  557. fn test_asin() {
  558. assert!(close(_0_0i.asin(), _0_0i));
  559. assert!(close(_1_0i.asin(), _1_0i.scale(f64::consts::PI/2.0)));
  560. assert!(close(_1_0i.scale(-1.0).asin(), _1_0i.scale(-f64::consts::PI/2.0)));
  561. assert!(close(_0_1i.asin(), _0_1i.scale((1.0 + 2.0.sqrt()).ln())));
  562. for &c in all_consts.iter() {
  563. // asin(conj(z)) = conj(asin(z))
  564. assert!(close(c.conj().asin(), c.asin().conj()));
  565. // asin(-z) = -asin(z)
  566. assert!(close(c.scale(-1.0).asin(), c.asin().scale(-1.0)));
  567. // for this branch, -pi/2 <= asin(z).re <= pi/2
  568. assert!(-f64::consts::PI/2.0 <= c.asin().re && c.asin().re <= f64::consts::PI/2.0);
  569. }
  570. }
  571. #[test]
  572. fn test_acos() {
  573. assert!(close(_0_0i.acos(), _1_0i.scale(f64::consts::PI/2.0)));
  574. assert!(close(_1_0i.acos(), _0_0i));
  575. assert!(close(_1_0i.scale(-1.0).acos(), _1_0i.scale(f64::consts::PI)));
  576. assert!(close(_0_1i.acos(), Complex::new(f64::consts::PI/2.0, (2.0.sqrt() - 1.0).ln())));
  577. for &c in all_consts.iter() {
  578. // acos(conj(z)) = conj(acos(z))
  579. assert!(close(c.conj().acos(), c.acos().conj()));
  580. // for this branch, 0 <= acos(z).re <= pi
  581. assert!(0.0 <= c.acos().re && c.acos().re <= f64::consts::PI);
  582. }
  583. }
  584. #[test]
  585. fn test_atan() {
  586. assert!(close(_0_0i.atan(), _0_0i));
  587. assert!(close(_1_0i.atan(), _1_0i.scale(f64::consts::PI/4.0)));
  588. assert!(close(_1_0i.scale(-1.0).atan(), _1_0i.scale(-f64::consts::PI/4.0)));
  589. assert!(close(_0_1i.atan(), Complex::new(0.0, f64::infinity())));
  590. for &c in all_consts.iter() {
  591. // atan(conj(z)) = conj(atan(z))
  592. assert!(close(c.conj().atan(), c.atan().conj()));
  593. // atan(-z) = -atan(z)
  594. assert!(close(c.scale(-1.0).atan(), c.atan().scale(-1.0)));
  595. // for this branch, -pi/2 <= atan(z).re <= pi/2
  596. assert!(-f64::consts::PI/2.0 <= c.atan().re && c.atan().re <= f64::consts::PI/2.0);
  597. }
  598. }
  599. #[test]
  600. fn test_sinh() {
  601. assert!(close(_0_0i.sinh(), _0_0i));
  602. assert!(close(_1_0i.sinh(), _1_0i.scale((f64::consts::E - 1.0/f64::consts::E)/2.0)));
  603. assert!(close(_0_1i.sinh(), _0_1i.scale(1.0.sin())));
  604. for &c in all_consts.iter() {
  605. // sinh(conj(z)) = conj(sinh(z))
  606. assert!(close(c.conj().sinh(), c.sinh().conj()));
  607. // sinh(-z) = -sinh(z)
  608. assert!(close(c.scale(-1.0).sinh(), c.sinh().scale(-1.0)));
  609. }
  610. }
  611. #[test]
  612. fn test_cosh() {
  613. assert!(close(_0_0i.cosh(), _1_0i));
  614. assert!(close(_1_0i.cosh(), _1_0i.scale((f64::consts::E + 1.0/f64::consts::E)/2.0)));
  615. assert!(close(_0_1i.cosh(), _1_0i.scale(1.0.cos())));
  616. for &c in all_consts.iter() {
  617. // cosh(conj(z)) = conj(cosh(z))
  618. assert!(close(c.conj().cosh(), c.cosh().conj()));
  619. // cosh(-z) = cosh(z)
  620. assert!(close(c.scale(-1.0).cosh(), c.cosh()));
  621. }
  622. }
  623. #[test]
  624. fn test_tanh() {
  625. assert!(close(_0_0i.tanh(), _0_0i));
  626. assert!(close(_1_0i.tanh(), _1_0i.scale((f64::consts::E.powi(2) - 1.0)/(f64::consts::E.powi(2) + 1.0))));
  627. assert!(close(_0_1i.tanh(), _0_1i.scale(1.0.tan())));
  628. for &c in all_consts.iter() {
  629. // tanh(conj(z)) = conj(tanh(z))
  630. assert!(close(c.conj().tanh(), c.conj().tanh()));
  631. // tanh(-z) = -tanh(z)
  632. assert!(close(c.scale(-1.0).tanh(), c.tanh().scale(-1.0)));
  633. }
  634. }
  635. #[test]
  636. fn test_asinh() {
  637. assert!(close(_0_0i.asinh(), _0_0i));
  638. assert!(close(_1_0i.asinh(), _1_0i.scale(1.0 + 2.0.sqrt()).ln()));
  639. assert!(close(_0_1i.asinh(), _0_1i.scale(f64::consts::PI/2.0)));
  640. assert!(close(_0_1i.asinh().scale(-1.0), _0_1i.scale(-f64::consts::PI/2.0)));
  641. for &c in all_consts.iter() {
  642. // asinh(conj(z)) = conj(asinh(z))
  643. assert!(close(c.conj().asinh(), c.conj().asinh()));
  644. // asinh(-z) = -asinh(z)
  645. assert!(close(c.scale(-1.0).asinh(), c.asinh().scale(-1.0)));
  646. // for this branch, -pi/2 <= asinh(z).im <= pi/2
  647. assert!(-f64::consts::PI/2.0 <= c.asinh().im && c.asinh().im <= f64::consts::PI/2.0);
  648. }
  649. }
  650. #[test]
  651. fn test_acosh() {
  652. assert!(close(_0_0i.acosh(), _0_1i.scale(f64::consts::PI/2.0)));
  653. assert!(close(_1_0i.acosh(), _0_0i));
  654. assert!(close(_1_0i.scale(-1.0).acosh(), _0_1i.scale(f64::consts::PI)));
  655. for &c in all_consts.iter() {
  656. // acosh(conj(z)) = conj(acosh(z))
  657. assert!(close(c.conj().acosh(), c.conj().acosh()));
  658. // for this branch, -pi <= acosh(z).im <= pi and 0 <= acosh(z).re
  659. assert!(-f64::consts::PI <= c.acosh().im && c.acosh().im <= f64::consts::PI && 0.0 <= c.cosh().re);
  660. }
  661. }
  662. #[test]
  663. fn test_atanh() {
  664. assert!(close(_0_0i.atanh(), _0_0i));
  665. assert!(close(_0_1i.atanh(), _0_1i.scale(f64::consts::PI/4.0)));
  666. assert!(close(_1_0i.atanh(), Complex::new(f64::infinity(), 0.0)));
  667. for &c in all_consts.iter() {
  668. // atanh(conj(z)) = conj(atanh(z))
  669. assert!(close(c.conj().atanh(), c.conj().atanh()));
  670. // atanh(-z) = -atanh(z)
  671. assert!(close(c.scale(-1.0).atanh(), c.atanh().scale(-1.0)));
  672. // for this branch, -pi/2 <= atanh(z).im <= pi/2
  673. assert!(-f64::consts::PI/2.0 <= c.atanh().im && c.atanh().im <= f64::consts::PI/2.0);
  674. }
  675. }
  676. #[test]
  677. fn test_exp_ln() {
  678. for &c in all_consts.iter() {
  679. // e^ln(z) = z
  680. assert!(close(c.ln().exp(), c));
  681. }
  682. }
  683. #[test]
  684. fn test_trig_to_hyperbolic() {
  685. for &c in all_consts.iter() {
  686. // sin(iz) = i sinh(z)
  687. assert!(close((_0_1i * c).sin(), _0_1i * c.sinh()));
  688. // cos(iz) = cosh(z)
  689. assert!(close((_0_1i * c).cos(), c.cosh()));
  690. // tan(iz) = i tanh(z)
  691. assert!(close((_0_1i * c).tan(), _0_1i * c.tanh()));
  692. }
  693. }
  694. #[test]
  695. fn test_trig_identities() {
  696. for &c in all_consts.iter() {
  697. // tan(z) = sin(z)/cos(z)
  698. assert!(close(c.tan(), c.sin()/c.cos()));
  699. // sin(z)^2 + cos(z)^2 = 1
  700. assert!(close(c.sin()*c.sin() + c.cos()*c.cos(), _1_0i));
  701. // sin(asin(z)) = z
  702. assert!(close(c.asin().sin(), c));
  703. // cos(acos(z)) = z
  704. assert!(close(c.acos().cos(), c));
  705. // tan(atan(z)) = z
  706. // i and -i are branch points
  707. if c != _0_1i && c != _0_1i.scale(-1.0) {
  708. assert!(close(c.atan().tan(), c));
  709. }
  710. // sin(z) = (e^(iz) - e^(-iz))/(2i)
  711. assert!(close(((_0_1i*c).exp() - (_0_1i*c).exp().inv())/_0_1i.scale(2.0), c.sin()));
  712. // cos(z) = (e^(iz) + e^(-iz))/2
  713. assert!(close(((_0_1i*c).exp() + (_0_1i*c).exp().inv()).unscale(2.0), c.cos()));
  714. // tan(z) = i (1 - e^(2iz))/(1 + e^(2iz))
  715. assert!(close(_0_1i * (_1_0i - (_0_1i*c).scale(2.0).exp())/(_1_0i + (_0_1i*c).scale(2.0).exp()), c.tan()));
  716. }
  717. }
  718. #[test]
  719. fn test_hyperbolic_identites() {
  720. for &c in all_consts.iter() {
  721. // tanh(z) = sinh(z)/cosh(z)
  722. assert!(close(c.tanh(), c.sinh()/c.cosh()));
  723. // cosh(z)^2 - sinh(z)^2 = 1
  724. assert!(close(c.cosh()*c.cosh() - c.sinh()*c.sinh(), _1_0i));
  725. // sinh(asinh(z)) = z
  726. assert!(close(c.asinh().sinh(), c));
  727. // cosh(acosh(z)) = z
  728. assert!(close(c.acosh().cosh(), c));
  729. // tanh(atanh(z)) = z
  730. // 1 and -1 are branch points
  731. if c != _1_0i && c != _1_0i.scale(-1.0) {
  732. assert!(close(c.atanh().tanh(), c));
  733. }
  734. // sinh(z) = (e^z - e^(-z))/2
  735. assert!(close((c.exp() - c.exp().inv()).unscale(2.0), c.sinh()));
  736. // cosh(z) = (e^z + e^(-z))/2
  737. assert!(close((c.exp() + c.exp().inv()).unscale(2.0), c.cosh()));
  738. // tanh(z) = ( e^(2z) - 1)/(e^(2z) + 1)
  739. assert!(close((c.scale(2.0).exp() - _1_0i)/(c.scale(2.0).exp() + _1_0i), c.tanh()));
  740. }
  741. }
  742. mod arith {
  743. use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts};
  744. use Zero;
  745. #[test]
  746. fn test_add() {
  747. assert_eq!(_05_05i + _05_05i, _1_1i);
  748. assert_eq!(_0_1i + _1_0i, _1_1i);
  749. assert_eq!(_1_0i + _neg1_1i, _0_1i);
  750. for &c in all_consts.iter() {
  751. assert_eq!(_0_0i + c, c);
  752. assert_eq!(c + _0_0i, c);
  753. }
  754. }
  755. #[test]
  756. fn test_sub() {
  757. assert_eq!(_05_05i - _05_05i, _0_0i);
  758. assert_eq!(_0_1i - _1_0i, _neg1_1i);
  759. assert_eq!(_0_1i - _neg1_1i, _1_0i);
  760. for &c in all_consts.iter() {
  761. assert_eq!(c - _0_0i, c);
  762. assert_eq!(c - c, _0_0i);
  763. }
  764. }
  765. #[test]
  766. fn test_mul() {
  767. assert_eq!(_05_05i * _05_05i, _0_1i.unscale(2.0));
  768. assert_eq!(_1_1i * _0_1i, _neg1_1i);
  769. // i^2 & i^4
  770. assert_eq!(_0_1i * _0_1i, -_1_0i);
  771. assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i);
  772. for &c in all_consts.iter() {
  773. assert_eq!(c * _1_0i, c);
  774. assert_eq!(_1_0i * c, c);
  775. }
  776. }
  777. #[test]
  778. fn test_div() {
  779. assert_eq!(_neg1_1i / _0_1i, _1_1i);
  780. for &c in all_consts.iter() {
  781. if c != Zero::zero() {
  782. assert_eq!(c / c, _1_0i);
  783. }
  784. }
  785. }
  786. #[test]
  787. fn test_neg() {
  788. assert_eq!(-_1_0i + _0_1i, _neg1_1i);
  789. assert_eq!((-_0_1i) * _0_1i, _1_0i);
  790. for &c in all_consts.iter() {
  791. assert_eq!(-(-c), c);
  792. }
  793. }
  794. }
  795. #[test]
  796. fn test_to_string() {
  797. fn test(c : Complex64, s: String) {
  798. assert_eq!(c.to_string(), s);
  799. }
  800. test(_0_0i, "0+0i".to_string());
  801. test(_1_0i, "1+0i".to_string());
  802. test(_0_1i, "0+1i".to_string());
  803. test(_1_1i, "1+1i".to_string());
  804. test(_neg1_1i, "-1+1i".to_string());
  805. test(-_neg1_1i, "1-1i".to_string());
  806. test(_05_05i, "0.5+0.5i".to_string());
  807. }
  808. #[test]
  809. fn test_hash() {
  810. let a = Complex::new(0i32, 0i32);
  811. let b = Complex::new(1i32, 0i32);
  812. let c = Complex::new(0i32, 1i32);
  813. assert!(::hash(&a) != ::hash(&b));
  814. assert!(::hash(&b) != ::hash(&c));
  815. assert!(::hash(&c) != ::hash(&a));
  816. }
  817. }