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.
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.
15 use std::num::{Zero,One,ToStrRadix};
17 // FIXME #1284: handle complex NaN & infinity etc. This
18 // probably doesn't map to C's _Complex correctly.
20 /// A complex number in Cartesian form.
22 pub struct Complex<T> {
23 /// Real portion of the complex number
25 /// Imaginary portion of the complex number
29 pub type Complex32 = Complex<f32>;
30 pub type Complex64 = Complex<f64>;
32 impl<T: Clone + Num> Complex<T> {
33 /// Create a new Complex
35 pub fn new(re: T, im: T) -> Complex<T> {
36 Complex { re: re, im: im }
40 Returns the square of the norm (since `T` doesn't necessarily
41 have a sqrt function), i.e. `re^2 + im^2`.
44 pub fn norm_sqr(&self) -> T {
45 self.re * self.re + self.im * self.im
49 /// Returns the complex conjugate. i.e. `re - i im`
51 pub fn conj(&self) -> Complex<T> {
52 Complex::new(self.re.clone(), -self.im)
56 /// Multiplies `self` by the scalar `t`.
58 pub fn scale(&self, t: T) -> Complex<T> {
59 Complex::new(self.re * t, self.im * t)
62 /// Divides `self` by the scalar `t`.
64 pub fn unscale(&self, t: T) -> Complex<T> {
65 Complex::new(self.re / t, self.im / t)
70 pub fn inv(&self) -> Complex<T> {
71 let norm_sqr = self.norm_sqr();
72 Complex::new(self.re / norm_sqr,
77 impl<T: Clone + FloatMath> Complex<T> {
80 pub fn norm(&self) -> T {
81 self.re.hypot(self.im)
85 impl<T: Clone + FloatMath> Complex<T> {
86 /// Calculate the principal Arg of self.
88 pub fn arg(&self) -> T {
89 self.im.atan2(self.re)
91 /// Convert to polar form (r, theta), such that `self = r * exp(i
94 pub fn to_polar(&self) -> (T, T) {
95 (self.norm(), self.arg())
97 /// Convert a polar representation into a complex number.
99 pub fn from_polar(r: &T, theta: &T) -> Complex<T> {
100 Complex::new(*r * theta.cos(), *r * theta.sin())
105 // (a + i b) + (c + i d) == (a + c) + i (b + d)
106 impl<T: Clone + Num> Add<Complex<T>, Complex<T>> for Complex<T> {
108 fn add(&self, other: &Complex<T>) -> Complex<T> {
109 Complex::new(self.re + other.re, self.im + other.im)
112 // (a + i b) - (c + i d) == (a - c) + i (b - d)
113 impl<T: Clone + Num> Sub<Complex<T>, Complex<T>> for Complex<T> {
115 fn sub(&self, other: &Complex<T>) -> Complex<T> {
116 Complex::new(self.re - other.re, self.im - other.im)
119 // (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c)
120 impl<T: Clone + Num> Mul<Complex<T>, Complex<T>> for Complex<T> {
122 fn mul(&self, other: &Complex<T>) -> Complex<T> {
123 Complex::new(self.re*other.re - self.im*other.im,
124 self.re*other.im + self.im*other.re)
128 // (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d)
129 // == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)]
130 impl<T: Clone + Num> Div<Complex<T>, Complex<T>> for Complex<T> {
132 fn div(&self, other: &Complex<T>) -> Complex<T> {
133 let norm_sqr = other.norm_sqr();
134 Complex::new((self.re*other.re + self.im*other.im) / norm_sqr,
135 (self.im*other.re - self.re*other.im) / norm_sqr)
139 impl<T: Clone + Num> Neg<Complex<T>> for Complex<T> {
141 fn neg(&self) -> Complex<T> {
142 Complex::new(-self.re, -self.im)
147 impl<T: Clone + Num> Zero for Complex<T> {
149 fn zero() -> Complex<T> {
150 Complex::new(Zero::zero(), Zero::zero())
154 fn is_zero(&self) -> bool {
155 self.re.is_zero() && self.im.is_zero()
159 impl<T: Clone + Num> One for Complex<T> {
161 fn one() -> Complex<T> {
162 Complex::new(One::one(), Zero::zero())
166 /* string conversions */
167 impl<T: fmt::Show + Num + Ord> fmt::Show for Complex<T> {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169 if self.im < Zero::zero() {
170 write!(f, "{}-{}i", self.re, -self.im)
172 write!(f, "{}+{}i", self.re, self.im)
177 impl<T: ToStrRadix + Num + Ord> ToStrRadix for Complex<T> {
178 fn to_str_radix(&self, radix: uint) -> String {
179 if self.im < Zero::zero() {
181 self.re.to_str_radix(radix),
182 (-self.im).to_str_radix(radix))
185 self.re.to_str_radix(radix),
186 self.im.to_str_radix(radix))
193 #![allow(non_uppercase_statics)]
195 use super::{Complex64, Complex};
196 use std::num::{Zero,One,Float};
198 pub static _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
199 pub static _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
200 pub static _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 };
201 pub static _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 };
202 pub static _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 };
203 pub static _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 };
204 pub static all_consts : [Complex64, .. 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i];
208 // check our constants are what Complex::new creates
209 fn test(c : Complex64, r : f64, i: f64) {
210 assert_eq!(c, Complex::new(r,i));
212 test(_0_0i, 0.0, 0.0);
213 test(_1_0i, 1.0, 0.0);
214 test(_1_1i, 1.0, 1.0);
215 test(_neg1_1i, -1.0, 1.0);
216 test(_05_05i, 0.5, 0.5);
218 assert_eq!(_0_0i, Zero::zero());
219 assert_eq!(_1_0i, One::one());
223 #[ignore(cfg(target_arch = "x86"))]
224 // FIXME #7158: (maybe?) currently failing on x86.
226 fn test(c: Complex64, ns: f64) {
227 assert_eq!(c.norm_sqr(), ns);
228 assert_eq!(c.norm(), ns.sqrt())
238 fn test_scale_unscale() {
239 assert_eq!(_05_05i.scale(2.0), _1_1i);
240 assert_eq!(_1_1i.unscale(2.0), _05_05i);
241 for &c in all_consts.iter() {
242 assert_eq!(c.scale(2.0).unscale(2.0), c);
248 for &c in all_consts.iter() {
249 assert_eq!(c.conj(), Complex::new(c.re, -c.im));
250 assert_eq!(c.conj().conj(), c);
256 assert_eq!(_1_1i.inv(), _05_05i.conj());
257 assert_eq!(_1_0i.inv(), _1_0i.inv());
264 // FIXME #5736: should this really fail, or just NaN?
270 fn test(c: Complex64, arg: f64) {
271 assert!((c.arg() - arg).abs() < 1.0e-6)
274 test(_1_1i, 0.25 * Float::pi());
275 test(_neg1_1i, 0.75 * Float::pi());
276 test(_05_05i, 0.25 * Float::pi());
280 fn test_polar_conv() {
281 fn test(c: Complex64) {
282 let (r, theta) = c.to_polar();
283 assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6);
285 for &c in all_consts.iter() { test(c); }
289 use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts};
294 assert_eq!(_05_05i + _05_05i, _1_1i);
295 assert_eq!(_0_1i + _1_0i, _1_1i);
296 assert_eq!(_1_0i + _neg1_1i, _0_1i);
298 for &c in all_consts.iter() {
299 assert_eq!(_0_0i + c, c);
300 assert_eq!(c + _0_0i, c);
306 assert_eq!(_05_05i - _05_05i, _0_0i);
307 assert_eq!(_0_1i - _1_0i, _neg1_1i);
308 assert_eq!(_0_1i - _neg1_1i, _1_0i);
310 for &c in all_consts.iter() {
311 assert_eq!(c - _0_0i, c);
312 assert_eq!(c - c, _0_0i);
318 assert_eq!(_05_05i * _05_05i, _0_1i.unscale(2.0));
319 assert_eq!(_1_1i * _0_1i, _neg1_1i);
322 assert_eq!(_0_1i * _0_1i, -_1_0i);
323 assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i);
325 for &c in all_consts.iter() {
326 assert_eq!(c * _1_0i, c);
327 assert_eq!(_1_0i * c, c);
332 assert_eq!(_neg1_1i / _0_1i, _1_1i);
333 for &c in all_consts.iter() {
334 if c != Zero::zero() {
335 assert_eq!(c / c, _1_0i);
341 assert_eq!(-_1_0i + _0_1i, _neg1_1i);
342 assert_eq!((-_0_1i) * _0_1i, _1_0i);
343 for &c in all_consts.iter() {
344 assert_eq!(-(-c), c);
351 fn test(c : Complex64, s: String) {
352 assert_eq!(c.to_str().to_string(), s);
354 test(_0_0i, "0+0i".to_string());
355 test(_1_0i, "1+0i".to_string());
356 test(_0_1i, "0+1i".to_string());
357 test(_1_1i, "1+1i".to_string());
358 test(_neg1_1i, "-1+1i".to_string());
359 test(-_neg1_1i, "1-1i".to_string());
360 test(_05_05i, "0.5+0.5i".to_string());