complex.rs 10 KB

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