complex.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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, RustcEncodable, RustcDecodable, Debug)]
  18. pub struct Complex<T> {
  19. /// Real portion of the complex number
  20. pub re: T,
  21. /// Imaginary portion of the complex number
  22. pub im: T
  23. }
  24. pub type Complex32 = Complex<f32>;
  25. pub type Complex64 = Complex<f64>;
  26. impl<T: Clone + Num> Complex<T> {
  27. /// Create a new Complex
  28. #[inline]
  29. pub fn new(re: T, im: T) -> Complex<T> {
  30. Complex { re: re, im: im }
  31. }
  32. /// Returns the square of the norm (since `T` doesn't necessarily
  33. /// have a sqrt function), i.e. `re^2 + im^2`.
  34. #[inline]
  35. pub fn norm_sqr(&self) -> T {
  36. self.re.clone() * self.re.clone() + self.im.clone() * self.im.clone()
  37. }
  38. /// Multiplies `self` by the scalar `t`.
  39. #[inline]
  40. pub fn scale(&self, t: T) -> Complex<T> {
  41. Complex::new(self.re.clone() * t.clone(), self.im.clone() * t)
  42. }
  43. /// Divides `self` by the scalar `t`.
  44. #[inline]
  45. pub fn unscale(&self, t: T) -> Complex<T> {
  46. Complex::new(self.re.clone() / t.clone(), self.im.clone() / t)
  47. }
  48. }
  49. impl<T: Clone + Num + Neg<Output = T>> Complex<T> {
  50. /// Returns the complex conjugate. i.e. `re - i im`
  51. #[inline]
  52. pub fn conj(&self) -> Complex<T> {
  53. Complex::new(self.re.clone(), -self.im.clone())
  54. }
  55. /// Returns `1/self`
  56. #[inline]
  57. pub fn inv(&self) -> Complex<T> {
  58. let norm_sqr = self.norm_sqr();
  59. Complex::new(self.re.clone() / norm_sqr.clone(),
  60. -self.im.clone() / norm_sqr)
  61. }
  62. }
  63. impl<T: Clone + Float> Complex<T> {
  64. /// Calculate |self|
  65. #[inline]
  66. pub fn norm(&self) -> T {
  67. self.re.clone().hypot(self.im.clone())
  68. }
  69. }
  70. impl<T: Clone + Float + Num> Complex<T> {
  71. /// Calculate the principal Arg of self.
  72. #[inline]
  73. pub fn arg(&self) -> T {
  74. self.im.clone().atan2(self.re.clone())
  75. }
  76. /// Convert to polar form (r, theta), such that `self = r * exp(i
  77. /// * theta)`
  78. #[inline]
  79. pub fn to_polar(&self) -> (T, T) {
  80. (self.norm(), self.arg())
  81. }
  82. /// Convert a polar representation into a complex number.
  83. #[inline]
  84. pub fn from_polar(r: &T, theta: &T) -> Complex<T> {
  85. Complex::new(*r * theta.cos(), *r * theta.sin())
  86. }
  87. }
  88. macro_rules! forward_val_val_binop {
  89. (impl $imp:ident, $method:ident) => {
  90. impl<T: Clone + Num> $imp<Complex<T>> for Complex<T> {
  91. type Output = Complex<T>;
  92. #[inline]
  93. fn $method(self, other: Complex<T>) -> Complex<T> {
  94. (&self).$method(&other)
  95. }
  96. }
  97. }
  98. }
  99. macro_rules! forward_ref_val_binop {
  100. (impl $imp:ident, $method:ident) => {
  101. impl<'a, T: Clone + Num> $imp<Complex<T>> for &'a Complex<T> {
  102. type Output = Complex<T>;
  103. #[inline]
  104. fn $method(self, other: Complex<T>) -> Complex<T> {
  105. self.$method(&other)
  106. }
  107. }
  108. }
  109. }
  110. macro_rules! forward_val_ref_binop {
  111. (impl $imp:ident, $method:ident) => {
  112. impl<'a, T: Clone + Num> $imp<&'a Complex<T>> for Complex<T> {
  113. type Output = Complex<T>;
  114. #[inline]
  115. fn $method(self, other: &Complex<T>) -> Complex<T> {
  116. (&self).$method(other)
  117. }
  118. }
  119. }
  120. }
  121. macro_rules! forward_all_binop {
  122. (impl $imp:ident, $method:ident) => {
  123. forward_val_val_binop!(impl $imp, $method);
  124. forward_ref_val_binop!(impl $imp, $method);
  125. forward_val_ref_binop!(impl $imp, $method);
  126. };
  127. }
  128. /* arithmetic */
  129. forward_all_binop!(impl Add, add);
  130. // (a + i b) + (c + i d) == (a + c) + i (b + d)
  131. impl<'a, 'b, T: Clone + Num> Add<&'b Complex<T>> for &'a Complex<T> {
  132. type Output = Complex<T>;
  133. #[inline]
  134. fn add(self, other: &Complex<T>) -> Complex<T> {
  135. Complex::new(self.re.clone() + other.re.clone(),
  136. self.im.clone() + other.im.clone())
  137. }
  138. }
  139. forward_all_binop!(impl Sub, sub);
  140. // (a + i b) - (c + i d) == (a - c) + i (b - d)
  141. impl<'a, 'b, T: Clone + Num> Sub<&'b Complex<T>> for &'a Complex<T> {
  142. type Output = Complex<T>;
  143. #[inline]
  144. fn sub(self, other: &Complex<T>) -> Complex<T> {
  145. Complex::new(self.re.clone() - other.re.clone(),
  146. self.im.clone() - other.im.clone())
  147. }
  148. }
  149. forward_all_binop!(impl Mul, mul);
  150. // (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c)
  151. impl<'a, 'b, T: Clone + Num> Mul<&'b Complex<T>> for &'a Complex<T> {
  152. type Output = Complex<T>;
  153. #[inline]
  154. fn mul(self, other: &Complex<T>) -> Complex<T> {
  155. Complex::new(self.re.clone() * other.re.clone() - self.im.clone() * other.im.clone(),
  156. self.re.clone() * other.im.clone() + self.im.clone() * other.re.clone())
  157. }
  158. }
  159. forward_all_binop!(impl Div, div);
  160. // (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d)
  161. // == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)]
  162. impl<'a, 'b, T: Clone + Num> Div<&'b Complex<T>> for &'a Complex<T> {
  163. type Output = Complex<T>;
  164. #[inline]
  165. fn div(self, other: &Complex<T>) -> Complex<T> {
  166. let norm_sqr = other.norm_sqr();
  167. Complex::new((self.re.clone() * other.re.clone() + self.im.clone() * other.im.clone()) / norm_sqr.clone(),
  168. (self.im.clone() * other.re.clone() - self.re.clone() * other.im.clone()) / norm_sqr)
  169. }
  170. }
  171. impl<T: Clone + Num + Neg<Output = T>> Neg for Complex<T> {
  172. type Output = Complex<T>;
  173. #[inline]
  174. fn neg(self) -> Complex<T> { -&self }
  175. }
  176. impl<'a, T: Clone + Num + Neg<Output = T>> Neg for &'a Complex<T> {
  177. type Output = Complex<T>;
  178. #[inline]
  179. fn neg(self) -> Complex<T> {
  180. Complex::new(-self.re.clone(), -self.im.clone())
  181. }
  182. }
  183. /* constants */
  184. impl<T: Clone + Num> Zero for Complex<T> {
  185. #[inline]
  186. fn zero() -> Complex<T> {
  187. Complex::new(Zero::zero(), Zero::zero())
  188. }
  189. #[inline]
  190. fn is_zero(&self) -> bool {
  191. self.re.is_zero() && self.im.is_zero()
  192. }
  193. }
  194. impl<T: Clone + Num> One for Complex<T> {
  195. #[inline]
  196. fn one() -> Complex<T> {
  197. Complex::new(One::one(), Zero::zero())
  198. }
  199. }
  200. /* string conversions */
  201. impl<T> fmt::Display for Complex<T> where
  202. T: fmt::Display + Num + PartialOrd + Clone
  203. {
  204. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  205. if self.im < Zero::zero() {
  206. write!(f, "{}-{}i", self.re, T::zero() - self.im.clone())
  207. } else {
  208. write!(f, "{}+{}i", self.re, self.im)
  209. }
  210. }
  211. }
  212. #[cfg(test)]
  213. mod test {
  214. #![allow(non_upper_case_globals)]
  215. use super::{Complex64, Complex};
  216. use std::f64;
  217. use {Zero, One, Float};
  218. pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
  219. pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
  220. pub const _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 };
  221. pub const _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 };
  222. pub const _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 };
  223. pub const _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 };
  224. pub const all_consts : [Complex64; 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i];
  225. #[test]
  226. fn test_consts() {
  227. // check our constants are what Complex::new creates
  228. fn test(c : Complex64, r : f64, i: f64) {
  229. assert_eq!(c, Complex::new(r,i));
  230. }
  231. test(_0_0i, 0.0, 0.0);
  232. test(_1_0i, 1.0, 0.0);
  233. test(_1_1i, 1.0, 1.0);
  234. test(_neg1_1i, -1.0, 1.0);
  235. test(_05_05i, 0.5, 0.5);
  236. assert_eq!(_0_0i, Zero::zero());
  237. assert_eq!(_1_0i, One::one());
  238. }
  239. #[test]
  240. #[cfg_attr(target_arch = "x86", ignore)]
  241. // FIXME #7158: (maybe?) currently failing on x86.
  242. fn test_norm() {
  243. fn test(c: Complex64, ns: f64) {
  244. assert_eq!(c.norm_sqr(), ns);
  245. assert_eq!(c.norm(), ns.sqrt())
  246. }
  247. test(_0_0i, 0.0);
  248. test(_1_0i, 1.0);
  249. test(_1_1i, 2.0);
  250. test(_neg1_1i, 2.0);
  251. test(_05_05i, 0.5);
  252. }
  253. #[test]
  254. fn test_scale_unscale() {
  255. assert_eq!(_05_05i.scale(2.0), _1_1i);
  256. assert_eq!(_1_1i.unscale(2.0), _05_05i);
  257. for &c in all_consts.iter() {
  258. assert_eq!(c.scale(2.0).unscale(2.0), c);
  259. }
  260. }
  261. #[test]
  262. fn test_conj() {
  263. for &c in all_consts.iter() {
  264. assert_eq!(c.conj(), Complex::new(c.re, -c.im));
  265. assert_eq!(c.conj().conj(), c);
  266. }
  267. }
  268. #[test]
  269. fn test_inv() {
  270. assert_eq!(_1_1i.inv(), _05_05i.conj());
  271. assert_eq!(_1_0i.inv(), _1_0i.inv());
  272. }
  273. #[test]
  274. #[should_panic]
  275. fn test_divide_by_zero_natural() {
  276. let n = Complex::new(2, 3);
  277. let d = Complex::new(0, 0);
  278. let _x = n / d;
  279. }
  280. #[test]
  281. #[should_panic]
  282. #[ignore]
  283. fn test_inv_zero() {
  284. // FIXME #5736: should this really fail, or just NaN?
  285. _0_0i.inv();
  286. }
  287. #[test]
  288. fn test_arg() {
  289. fn test(c: Complex64, arg: f64) {
  290. assert!((c.arg() - arg).abs() < 1.0e-6)
  291. }
  292. test(_1_0i, 0.0);
  293. test(_1_1i, 0.25 * f64::consts::PI);
  294. test(_neg1_1i, 0.75 * f64::consts::PI);
  295. test(_05_05i, 0.25 * f64::consts::PI);
  296. }
  297. #[test]
  298. fn test_polar_conv() {
  299. fn test(c: Complex64) {
  300. let (r, theta) = c.to_polar();
  301. assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6);
  302. }
  303. for &c in all_consts.iter() { test(c); }
  304. }
  305. mod arith {
  306. use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts};
  307. use Zero;
  308. #[test]
  309. fn test_add() {
  310. assert_eq!(_05_05i + _05_05i, _1_1i);
  311. assert_eq!(_0_1i + _1_0i, _1_1i);
  312. assert_eq!(_1_0i + _neg1_1i, _0_1i);
  313. for &c in all_consts.iter() {
  314. assert_eq!(_0_0i + c, c);
  315. assert_eq!(c + _0_0i, c);
  316. }
  317. }
  318. #[test]
  319. fn test_sub() {
  320. assert_eq!(_05_05i - _05_05i, _0_0i);
  321. assert_eq!(_0_1i - _1_0i, _neg1_1i);
  322. assert_eq!(_0_1i - _neg1_1i, _1_0i);
  323. for &c in all_consts.iter() {
  324. assert_eq!(c - _0_0i, c);
  325. assert_eq!(c - c, _0_0i);
  326. }
  327. }
  328. #[test]
  329. fn test_mul() {
  330. assert_eq!(_05_05i * _05_05i, _0_1i.unscale(2.0));
  331. assert_eq!(_1_1i * _0_1i, _neg1_1i);
  332. // i^2 & i^4
  333. assert_eq!(_0_1i * _0_1i, -_1_0i);
  334. assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i);
  335. for &c in all_consts.iter() {
  336. assert_eq!(c * _1_0i, c);
  337. assert_eq!(_1_0i * c, c);
  338. }
  339. }
  340. #[test]
  341. fn test_div() {
  342. assert_eq!(_neg1_1i / _0_1i, _1_1i);
  343. for &c in all_consts.iter() {
  344. if c != Zero::zero() {
  345. assert_eq!(c / c, _1_0i);
  346. }
  347. }
  348. }
  349. #[test]
  350. fn test_neg() {
  351. assert_eq!(-_1_0i + _0_1i, _neg1_1i);
  352. assert_eq!((-_0_1i) * _0_1i, _1_0i);
  353. for &c in all_consts.iter() {
  354. assert_eq!(-(-c), c);
  355. }
  356. }
  357. }
  358. #[test]
  359. fn test_to_string() {
  360. fn test(c : Complex64, s: String) {
  361. assert_eq!(c.to_string(), s);
  362. }
  363. test(_0_0i, "0+0i".to_string());
  364. test(_1_0i, "1+0i".to_string());
  365. test(_0_1i, "0+1i".to_string());
  366. test(_1_1i, "1+1i".to_string());
  367. test(_neg1_1i, "-1+1i".to_string());
  368. test(-_neg1_1i, "1-1i".to_string());
  369. test(_05_05i, "0.5+0.5i".to_string());
  370. }
  371. #[test]
  372. fn test_hash() {
  373. let a = Complex::new(0i32, 0i32);
  374. let b = Complex::new(1i32, 0i32);
  375. let c = Complex::new(0i32, 1i32);
  376. assert!(::hash(&a) != ::hash(&b));
  377. assert!(::hash(&b) != ::hash(&c));
  378. assert!(::hash(&c) != ::hash(&a));
  379. }
  380. }