complex.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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::num::FloatMath;
  13. use std::iter::{AdditiveIterator, MultiplicativeIterator};
  14. use {Zero, One, Num};
  15. // FIXME #1284: handle complex NaN & infinity etc. This
  16. // probably doesn't map to C's _Complex correctly.
  17. /// A complex number in Cartesian form.
  18. #[deriving(PartialEq, Copy, Clone, Hash, Encodable, Decodable)]
  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 * self.re + self.im * self.im
  38. }
  39. /// Returns the complex conjugate. i.e. `re - i im`
  40. #[inline]
  41. pub fn conj(&self) -> Complex<T> {
  42. Complex::new(self.re.clone(), -self.im)
  43. }
  44. /// Multiplies `self` by the scalar `t`.
  45. #[inline]
  46. pub fn scale(&self, t: T) -> Complex<T> {
  47. Complex::new(self.re * t, self.im * t)
  48. }
  49. /// Divides `self` by the scalar `t`.
  50. #[inline]
  51. pub fn unscale(&self, t: T) -> Complex<T> {
  52. Complex::new(self.re / t, self.im / t)
  53. }
  54. /// Returns `1/self`
  55. #[inline]
  56. pub fn inv(&self) -> Complex<T> {
  57. let norm_sqr = self.norm_sqr();
  58. Complex::new(self.re / norm_sqr,
  59. -self.im / norm_sqr)
  60. }
  61. }
  62. impl<T: Clone + FloatMath> Complex<T> {
  63. /// Calculate |self|
  64. #[inline]
  65. pub fn norm(&self) -> T {
  66. self.re.hypot(self.im)
  67. }
  68. }
  69. impl<T: Clone + FloatMath + Num> Complex<T> {
  70. /// Calculate the principal Arg of self.
  71. #[inline]
  72. pub fn arg(&self) -> T {
  73. self.im.atan2(self.re)
  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. }
  87. /* arithmetic */
  88. // (a + i b) + (c + i d) == (a + c) + i (b + d)
  89. impl<T: Clone + Num> Add<Complex<T>, Complex<T>> for Complex<T> {
  90. #[inline]
  91. fn add(&self, other: &Complex<T>) -> Complex<T> {
  92. Complex::new(self.re + other.re, self.im + other.im)
  93. }
  94. }
  95. // (a + i b) - (c + i d) == (a - c) + i (b - d)
  96. impl<T: Clone + Num> Sub<Complex<T>, Complex<T>> for Complex<T> {
  97. #[inline]
  98. fn sub(&self, other: &Complex<T>) -> Complex<T> {
  99. Complex::new(self.re - other.re, self.im - other.im)
  100. }
  101. }
  102. // (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c)
  103. impl<T: Clone + Num> Mul<Complex<T>, Complex<T>> for Complex<T> {
  104. #[inline]
  105. fn mul(&self, other: &Complex<T>) -> Complex<T> {
  106. Complex::new(self.re*other.re - self.im*other.im,
  107. self.re*other.im + self.im*other.re)
  108. }
  109. }
  110. // (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d)
  111. // == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)]
  112. impl<T: Clone + Num> Div<Complex<T>, Complex<T>> for Complex<T> {
  113. #[inline]
  114. fn div(&self, other: &Complex<T>) -> Complex<T> {
  115. let norm_sqr = other.norm_sqr();
  116. Complex::new((self.re*other.re + self.im*other.im) / norm_sqr,
  117. (self.im*other.re - self.re*other.im) / norm_sqr)
  118. }
  119. }
  120. impl<T: Clone + Num> Neg<Complex<T>> for Complex<T> {
  121. #[inline]
  122. fn neg(&self) -> Complex<T> {
  123. Complex::new(-self.re, -self.im)
  124. }
  125. }
  126. /* constants */
  127. impl<T: Clone + Num> Zero for Complex<T> {
  128. #[inline]
  129. fn zero() -> Complex<T> {
  130. Complex::new(Zero::zero(), Zero::zero())
  131. }
  132. #[inline]
  133. fn is_zero(&self) -> bool {
  134. self.re.is_zero() && self.im.is_zero()
  135. }
  136. }
  137. impl<T: Clone + Num> One for Complex<T> {
  138. #[inline]
  139. fn one() -> Complex<T> {
  140. Complex::new(One::one(), Zero::zero())
  141. }
  142. }
  143. /* string conversions */
  144. impl<T: fmt::Show + Num + PartialOrd> fmt::Show for Complex<T> {
  145. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  146. if self.im < Zero::zero() {
  147. write!(f, "{}-{}i", self.re, -self.im)
  148. } else {
  149. write!(f, "{}+{}i", self.re, self.im)
  150. }
  151. }
  152. }
  153. impl<A: Clone + Num, T: Iterator<Complex<A>>> AdditiveIterator<Complex<A>> for T {
  154. fn sum(self) -> Complex<A> {
  155. let init: Complex<A> = Zero::zero();
  156. self.fold(init, |acc, x| acc + x)
  157. }
  158. }
  159. impl<A: Clone + Num, T: Iterator<Complex<A>>> MultiplicativeIterator<Complex<A>> for T {
  160. fn product(self) -> Complex<A> {
  161. let init: Complex<A> = One::one();
  162. self.fold(init, |acc, x| acc * x)
  163. }
  164. }
  165. #[cfg(test)]
  166. mod test {
  167. #![allow(non_upper_case_globals)]
  168. use super::{Complex64, Complex};
  169. use std::f64;
  170. use std::num::Float;
  171. use std::hash::hash;
  172. use {Zero, One};
  173. pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
  174. pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
  175. pub const _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 };
  176. pub const _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 };
  177. pub const _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 };
  178. pub const _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 };
  179. pub const all_consts : [Complex64, .. 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i];
  180. #[test]
  181. fn test_consts() {
  182. // check our constants are what Complex::new creates
  183. fn test(c : Complex64, r : f64, i: f64) {
  184. assert_eq!(c, Complex::new(r,i));
  185. }
  186. test(_0_0i, 0.0, 0.0);
  187. test(_1_0i, 1.0, 0.0);
  188. test(_1_1i, 1.0, 1.0);
  189. test(_neg1_1i, -1.0, 1.0);
  190. test(_05_05i, 0.5, 0.5);
  191. assert_eq!(_0_0i, Zero::zero());
  192. assert_eq!(_1_0i, One::one());
  193. }
  194. #[test]
  195. #[cfg_attr(target_arch = "x86", ignore)]
  196. // FIXME #7158: (maybe?) currently failing on x86.
  197. fn test_norm() {
  198. fn test(c: Complex64, ns: f64) {
  199. assert_eq!(c.norm_sqr(), ns);
  200. assert_eq!(c.norm(), ns.sqrt())
  201. }
  202. test(_0_0i, 0.0);
  203. test(_1_0i, 1.0);
  204. test(_1_1i, 2.0);
  205. test(_neg1_1i, 2.0);
  206. test(_05_05i, 0.5);
  207. }
  208. #[test]
  209. fn test_scale_unscale() {
  210. assert_eq!(_05_05i.scale(2.0), _1_1i);
  211. assert_eq!(_1_1i.unscale(2.0), _05_05i);
  212. for &c in all_consts.iter() {
  213. assert_eq!(c.scale(2.0).unscale(2.0), c);
  214. }
  215. }
  216. #[test]
  217. fn test_conj() {
  218. for &c in all_consts.iter() {
  219. assert_eq!(c.conj(), Complex::new(c.re, -c.im));
  220. assert_eq!(c.conj().conj(), c);
  221. }
  222. }
  223. #[test]
  224. fn test_inv() {
  225. assert_eq!(_1_1i.inv(), _05_05i.conj());
  226. assert_eq!(_1_0i.inv(), _1_0i.inv());
  227. }
  228. #[test]
  229. #[should_fail]
  230. fn test_divide_by_zero_natural() {
  231. let n = Complex::new(2i, 3i);
  232. let d = Complex::new(0, 0);
  233. let _x = n / d;
  234. }
  235. #[test]
  236. #[should_fail]
  237. #[ignore]
  238. fn test_inv_zero() {
  239. // FIXME #5736: should this really fail, or just NaN?
  240. _0_0i.inv();
  241. }
  242. #[test]
  243. fn test_arg() {
  244. fn test(c: Complex64, arg: f64) {
  245. assert!((c.arg() - arg).abs() < 1.0e-6)
  246. }
  247. test(_1_0i, 0.0);
  248. test(_1_1i, 0.25 * f64::consts::PI);
  249. test(_neg1_1i, 0.75 * f64::consts::PI);
  250. test(_05_05i, 0.25 * f64::consts::PI);
  251. }
  252. #[test]
  253. fn test_polar_conv() {
  254. fn test(c: Complex64) {
  255. let (r, theta) = c.to_polar();
  256. assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6);
  257. }
  258. for &c in all_consts.iter() { test(c); }
  259. }
  260. mod arith {
  261. use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts};
  262. use Zero;
  263. #[test]
  264. fn test_add() {
  265. assert_eq!(_05_05i + _05_05i, _1_1i);
  266. assert_eq!(_0_1i + _1_0i, _1_1i);
  267. assert_eq!(_1_0i + _neg1_1i, _0_1i);
  268. for &c in all_consts.iter() {
  269. assert_eq!(_0_0i + c, c);
  270. assert_eq!(c + _0_0i, c);
  271. }
  272. }
  273. #[test]
  274. fn test_sub() {
  275. assert_eq!(_05_05i - _05_05i, _0_0i);
  276. assert_eq!(_0_1i - _1_0i, _neg1_1i);
  277. assert_eq!(_0_1i - _neg1_1i, _1_0i);
  278. for &c in all_consts.iter() {
  279. assert_eq!(c - _0_0i, c);
  280. assert_eq!(c - c, _0_0i);
  281. }
  282. }
  283. #[test]
  284. fn test_mul() {
  285. assert_eq!(_05_05i * _05_05i, _0_1i.unscale(2.0));
  286. assert_eq!(_1_1i * _0_1i, _neg1_1i);
  287. // i^2 & i^4
  288. assert_eq!(_0_1i * _0_1i, -_1_0i);
  289. assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i);
  290. for &c in all_consts.iter() {
  291. assert_eq!(c * _1_0i, c);
  292. assert_eq!(_1_0i * c, c);
  293. }
  294. }
  295. #[test]
  296. fn test_div() {
  297. assert_eq!(_neg1_1i / _0_1i, _1_1i);
  298. for &c in all_consts.iter() {
  299. if c != Zero::zero() {
  300. assert_eq!(c / c, _1_0i);
  301. }
  302. }
  303. }
  304. #[test]
  305. fn test_neg() {
  306. assert_eq!(-_1_0i + _0_1i, _neg1_1i);
  307. assert_eq!((-_0_1i) * _0_1i, _1_0i);
  308. for &c in all_consts.iter() {
  309. assert_eq!(-(-c), c);
  310. }
  311. }
  312. }
  313. #[test]
  314. fn test_to_string() {
  315. fn test(c : Complex64, s: String) {
  316. assert_eq!(c.to_string(), s);
  317. }
  318. test(_0_0i, "0+0i".to_string());
  319. test(_1_0i, "1+0i".to_string());
  320. test(_0_1i, "0+1i".to_string());
  321. test(_1_1i, "1+1i".to_string());
  322. test(_neg1_1i, "-1+1i".to_string());
  323. test(-_neg1_1i, "1-1i".to_string());
  324. test(_05_05i, "0.5+0.5i".to_string());
  325. }
  326. #[test]
  327. fn test_hash() {
  328. let a = Complex::new(0i32, 0i32);
  329. let b = Complex::new(1i32, 0i32);
  330. let c = Complex::new(0i32, 1i32);
  331. assert!(hash(&a) != hash(&b));
  332. assert!(hash(&b) != hash(&c));
  333. assert!(hash(&c) != hash(&a));
  334. }
  335. }