]> git.proxmox.com Git - rustc.git/blob - src/vendor/num-complex/src/lib.rs
New upstream version 1.19.0+dfsg1
[rustc.git] / src / vendor / num-complex / src / lib.rs
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
11 //! Complex numbers.
12 #![doc(html_logo_url = "https://rust-num.github.io/num/rust-logo-128x128-blk-v2.png",
13 html_favicon_url = "https://rust-num.github.io/num/favicon.ico",
14 html_root_url = "https://rust-num.github.io/num/",
15 html_playground_url = "http://play.integer32.com/")]
16
17 extern crate num_traits as traits;
18
19 #[cfg(feature = "rustc-serialize")]
20 extern crate rustc_serialize;
21
22 #[cfg(feature = "serde")]
23 extern crate serde;
24
25 use std::fmt;
26 #[cfg(test)]
27 use std::hash;
28 use std::ops::{Add, Div, Mul, Neg, Sub};
29
30 use traits::{Zero, One, Num, Float};
31
32 // FIXME #1284: handle complex NaN & infinity etc. This
33 // probably doesn't map to C's _Complex correctly.
34
35 /// A complex number in Cartesian form.
36 ///
37 /// ## Representation and Foreign Function Interface Compatibility
38 ///
39 /// `Complex<T>` is memory layout compatible with an array `[T; 2]`.
40 ///
41 /// Note that `Complex<F>` where F is a floating point type is **only** memory
42 /// layout compatible with C's complex types, **not** necessarily calling
43 /// convention compatible. This means that for FFI you can only pass
44 /// `Complex<F>` behind a pointer, not as a value.
45 ///
46 /// ## Examples
47 ///
48 /// Example of extern function declaration.
49 ///
50 /// ```
51 /// use num_complex::Complex;
52 /// use std::os::raw::c_int;
53 ///
54 /// extern "C" {
55 /// fn zaxpy_(n: *const c_int, alpha: *const Complex<f64>,
56 /// x: *const Complex<f64>, incx: *const c_int,
57 /// y: *mut Complex<f64>, incy: *const c_int);
58 /// }
59 /// ```
60 #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default)]
61 #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
62 #[repr(C)]
63 pub struct Complex<T> {
64 /// Real portion of the complex number
65 pub re: T,
66 /// Imaginary portion of the complex number
67 pub im: T
68 }
69
70 pub type Complex32 = Complex<f32>;
71 pub type Complex64 = Complex<f64>;
72
73 impl<T: Clone + Num> Complex<T> {
74 /// Create a new Complex
75 #[inline]
76 pub fn new(re: T, im: T) -> Complex<T> {
77 Complex { re: re, im: im }
78 }
79
80 /// Returns imaginary unit
81 #[inline]
82 pub fn i() -> Complex<T> {
83 Self::new(T::zero(), T::one())
84 }
85
86 /// Returns the square of the norm (since `T` doesn't necessarily
87 /// have a sqrt function), i.e. `re^2 + im^2`.
88 #[inline]
89 pub fn norm_sqr(&self) -> T {
90 self.re.clone() * self.re.clone() + self.im.clone() * self.im.clone()
91 }
92
93 /// Multiplies `self` by the scalar `t`.
94 #[inline]
95 pub fn scale(&self, t: T) -> Complex<T> {
96 Complex::new(self.re.clone() * t.clone(), self.im.clone() * t)
97 }
98
99 /// Divides `self` by the scalar `t`.
100 #[inline]
101 pub fn unscale(&self, t: T) -> Complex<T> {
102 Complex::new(self.re.clone() / t.clone(), self.im.clone() / t)
103 }
104 }
105
106 impl<T: Clone + Num + Neg<Output = T>> Complex<T> {
107 /// Returns the complex conjugate. i.e. `re - i im`
108 #[inline]
109 pub fn conj(&self) -> Complex<T> {
110 Complex::new(self.re.clone(), -self.im.clone())
111 }
112
113 /// Returns `1/self`
114 #[inline]
115 pub fn inv(&self) -> Complex<T> {
116 let norm_sqr = self.norm_sqr();
117 Complex::new(self.re.clone() / norm_sqr.clone(),
118 -self.im.clone() / norm_sqr)
119 }
120 }
121
122 impl<T: Clone + Float> Complex<T> {
123 /// Calculate |self|
124 #[inline]
125 pub fn norm(&self) -> T {
126 self.re.hypot(self.im)
127 }
128 /// Calculate the principal Arg of self.
129 #[inline]
130 pub fn arg(&self) -> T {
131 self.im.atan2(self.re)
132 }
133 /// Convert to polar form (r, theta), such that `self = r * exp(i
134 /// * theta)`
135 #[inline]
136 pub fn to_polar(&self) -> (T, T) {
137 (self.norm(), self.arg())
138 }
139 /// Convert a polar representation into a complex number.
140 #[inline]
141 pub fn from_polar(r: &T, theta: &T) -> Complex<T> {
142 Complex::new(*r * theta.cos(), *r * theta.sin())
143 }
144
145 /// Computes `e^(self)`, where `e` is the base of the natural logarithm.
146 #[inline]
147 pub fn exp(&self) -> Complex<T> {
148 // formula: e^(a + bi) = e^a (cos(b) + i*sin(b))
149 // = from_polar(e^a, b)
150 Complex::from_polar(&self.re.exp(), &self.im)
151 }
152
153 /// Computes the principal value of natural logarithm of `self`.
154 ///
155 /// This function has one branch cut:
156 ///
157 /// * `(-∞, 0]`, continuous from above.
158 ///
159 /// The branch satisfies `-π ≤ arg(ln(z)) ≤ π`.
160 #[inline]
161 pub fn ln(&self) -> Complex<T> {
162 // formula: ln(z) = ln|z| + i*arg(z)
163 let (r, theta) = self.to_polar();
164 Complex::new(r.ln(), theta)
165 }
166
167 /// Computes the principal value of the square root of `self`.
168 ///
169 /// This function has one branch cut:
170 ///
171 /// * `(-∞, 0)`, continuous from above.
172 ///
173 /// The branch satisfies `-π/2 ≤ arg(sqrt(z)) ≤ π/2`.
174 #[inline]
175 pub fn sqrt(&self) -> Complex<T> {
176 // formula: sqrt(r e^(it)) = sqrt(r) e^(it/2)
177 let two = T::one() + T::one();
178 let (r, theta) = self.to_polar();
179 Complex::from_polar(&(r.sqrt()), &(theta/two))
180 }
181
182 /// Raises `self` to a floating point power.
183 #[inline]
184 pub fn powf(&self, exp: T) -> Complex<T> {
185 // formula: x^y = (ρ e^(i θ))^y = ρ^y e^(i θ y)
186 // = from_polar(ρ^y, θ y)
187 let (r, theta) = self.to_polar();
188 Complex::from_polar(&r.powf(exp), &(theta*exp))
189 }
190
191 /// Returns the logarithm of `self` with respect to an arbitrary base.
192 #[inline]
193 pub fn log(&self, base: T) -> Complex<T> {
194 // formula: log_y(x) = log_y(ρ e^(i θ))
195 // = log_y(ρ) + log_y(e^(i θ)) = log_y(ρ) + ln(e^(i θ)) / ln(y)
196 // = log_y(ρ) + i θ / ln(y)
197 let (r, theta) = self.to_polar();
198 Complex::new(r.log(base), theta / base.ln())
199 }
200
201 /// Raises `self` to a complex power.
202 #[inline]
203 pub fn powc(&self, exp: Complex<T>) -> Complex<T> {
204 // formula: x^y = (a + i b)^(c + i d)
205 // = (ρ e^(i θ))^c (ρ e^(i θ))^(i d)
206 // where ρ=|x| and θ=arg(x)
207 // = ρ^c e^(−d θ) e^(i c θ) ρ^(i d)
208 // = p^c e^(−d θ) (cos(c θ)
209 // + i sin(c θ)) (cos(d ln(ρ)) + i sin(d ln(ρ)))
210 // = p^c e^(−d θ) (
211 // cos(c θ) cos(d ln(ρ)) − sin(c θ) sin(d ln(ρ))
212 // + i(cos(c θ) sin(d ln(ρ)) + sin(c θ) cos(d ln(ρ))))
213 // = p^c e^(−d θ) (cos(c θ + d ln(ρ)) + i sin(c θ + d ln(ρ)))
214 // = from_polar(p^c e^(−d θ), c θ + d ln(ρ))
215 let (r, theta) = self.to_polar();
216 Complex::from_polar(
217 &(r.powf(exp.re) * (-exp.im * theta).exp()),
218 &(exp.re * theta + exp.im * r.ln()))
219 }
220
221 /// Raises a floating point number to the complex power `self`.
222 #[inline]
223 pub fn expf(&self, base: T) -> Complex<T> {
224 // formula: x^(a+bi) = x^a x^bi = x^a e^(b ln(x) i)
225 // = from_polar(x^a, b ln(x))
226 Complex::from_polar(&base.powf(self.re), &(self.im * base.ln()))
227 }
228
229 /// Computes the sine of `self`.
230 #[inline]
231 pub fn sin(&self) -> Complex<T> {
232 // formula: sin(a + bi) = sin(a)cosh(b) + i*cos(a)sinh(b)
233 Complex::new(self.re.sin() * self.im.cosh(), self.re.cos() * self.im.sinh())
234 }
235
236 /// Computes the cosine of `self`.
237 #[inline]
238 pub fn cos(&self) -> Complex<T> {
239 // formula: cos(a + bi) = cos(a)cosh(b) - i*sin(a)sinh(b)
240 Complex::new(self.re.cos() * self.im.cosh(), -self.re.sin() * self.im.sinh())
241 }
242
243 /// Computes the tangent of `self`.
244 #[inline]
245 pub fn tan(&self) -> Complex<T> {
246 // formula: tan(a + bi) = (sin(2a) + i*sinh(2b))/(cos(2a) + cosh(2b))
247 let (two_re, two_im) = (self.re + self.re, self.im + self.im);
248 Complex::new(two_re.sin(), two_im.sinh()).unscale(two_re.cos() + two_im.cosh())
249 }
250
251 /// Computes the principal value of the inverse sine of `self`.
252 ///
253 /// This function has two branch cuts:
254 ///
255 /// * `(-∞, -1)`, continuous from above.
256 /// * `(1, ∞)`, continuous from below.
257 ///
258 /// The branch satisfies `-π/2 ≤ Re(asin(z)) ≤ π/2`.
259 #[inline]
260 pub fn asin(&self) -> Complex<T> {
261 // formula: arcsin(z) = -i ln(sqrt(1-z^2) + iz)
262 let i = Complex::i();
263 -i*((Complex::one() - self*self).sqrt() + i*self).ln()
264 }
265
266 /// Computes the principal value of the inverse cosine of `self`.
267 ///
268 /// This function has two branch cuts:
269 ///
270 /// * `(-∞, -1)`, continuous from above.
271 /// * `(1, ∞)`, continuous from below.
272 ///
273 /// The branch satisfies `0 ≤ Re(acos(z)) ≤ π`.
274 #[inline]
275 pub fn acos(&self) -> Complex<T> {
276 // formula: arccos(z) = -i ln(i sqrt(1-z^2) + z)
277 let i = Complex::i();
278 -i*(i*(Complex::one() - self*self).sqrt() + self).ln()
279 }
280
281 /// Computes the principal value of the inverse tangent of `self`.
282 ///
283 /// This function has two branch cuts:
284 ///
285 /// * `(-∞i, -i]`, continuous from the left.
286 /// * `[i, ∞i)`, continuous from the right.
287 ///
288 /// The branch satisfies `-π/2 ≤ Re(atan(z)) ≤ π/2`.
289 #[inline]
290 pub fn atan(&self) -> Complex<T> {
291 // formula: arctan(z) = (ln(1+iz) - ln(1-iz))/(2i)
292 let i = Complex::i();
293 let one = Complex::one();
294 let two = one + one;
295 if *self == i {
296 return Complex::new(T::zero(), T::infinity());
297 }
298 else if *self == -i {
299 return Complex::new(T::zero(), -T::infinity());
300 }
301 ((one + i * self).ln() - (one - i * self).ln()) / (two * i)
302 }
303
304 /// Computes the hyperbolic sine of `self`.
305 #[inline]
306 pub fn sinh(&self) -> Complex<T> {
307 // formula: sinh(a + bi) = sinh(a)cos(b) + i*cosh(a)sin(b)
308 Complex::new(self.re.sinh() * self.im.cos(), self.re.cosh() * self.im.sin())
309 }
310
311 /// Computes the hyperbolic cosine of `self`.
312 #[inline]
313 pub fn cosh(&self) -> Complex<T> {
314 // formula: cosh(a + bi) = cosh(a)cos(b) + i*sinh(a)sin(b)
315 Complex::new(self.re.cosh() * self.im.cos(), self.re.sinh() * self.im.sin())
316 }
317
318 /// Computes the hyperbolic tangent of `self`.
319 #[inline]
320 pub fn tanh(&self) -> Complex<T> {
321 // formula: tanh(a + bi) = (sinh(2a) + i*sin(2b))/(cosh(2a) + cos(2b))
322 let (two_re, two_im) = (self.re + self.re, self.im + self.im);
323 Complex::new(two_re.sinh(), two_im.sin()).unscale(two_re.cosh() + two_im.cos())
324 }
325
326 /// Computes the principal value of inverse hyperbolic sine of `self`.
327 ///
328 /// This function has two branch cuts:
329 ///
330 /// * `(-∞i, -i)`, continuous from the left.
331 /// * `(i, ∞i)`, continuous from the right.
332 ///
333 /// The branch satisfies `-π/2 ≤ Im(asinh(z)) ≤ π/2`.
334 #[inline]
335 pub fn asinh(&self) -> Complex<T> {
336 // formula: arcsinh(z) = ln(z + sqrt(1+z^2))
337 let one = Complex::one();
338 (self + (one + self * self).sqrt()).ln()
339 }
340
341 /// Computes the principal value of inverse hyperbolic cosine of `self`.
342 ///
343 /// This function has one branch cut:
344 ///
345 /// * `(-∞, 1)`, continuous from above.
346 ///
347 /// The branch satisfies `-π ≤ Im(acosh(z)) ≤ π` and `0 ≤ Re(acosh(z)) < ∞`.
348 #[inline]
349 pub fn acosh(&self) -> Complex<T> {
350 // formula: arccosh(z) = 2 ln(sqrt((z+1)/2) + sqrt((z-1)/2))
351 let one = Complex::one();
352 let two = one + one;
353 two * (((self + one)/two).sqrt() + ((self - one)/two).sqrt()).ln()
354 }
355
356 /// Computes the principal value of inverse hyperbolic tangent of `self`.
357 ///
358 /// This function has two branch cuts:
359 ///
360 /// * `(-∞, -1]`, continuous from above.
361 /// * `[1, ∞)`, continuous from below.
362 ///
363 /// The branch satisfies `-π/2 ≤ Im(atanh(z)) ≤ π/2`.
364 #[inline]
365 pub fn atanh(&self) -> Complex<T> {
366 // formula: arctanh(z) = (ln(1+z) - ln(1-z))/2
367 let one = Complex::one();
368 let two = one + one;
369 if *self == one {
370 return Complex::new(T::infinity(), T::zero());
371 }
372 else if *self == -one {
373 return Complex::new(-T::infinity(), T::zero());
374 }
375 ((one + self).ln() - (one - self).ln()) / two
376 }
377
378 /// Checks if the given complex number is NaN
379 #[inline]
380 pub fn is_nan(self) -> bool {
381 self.re.is_nan() || self.im.is_nan()
382 }
383
384 /// Checks if the given complex number is infinite
385 #[inline]
386 pub fn is_infinite(self) -> bool {
387 !self.is_nan() && (self.re.is_infinite() || self.im.is_infinite())
388 }
389
390 /// Checks if the given complex number is finite
391 #[inline]
392 pub fn is_finite(self) -> bool {
393 self.re.is_finite() && self.im.is_finite()
394 }
395
396 /// Checks if the given complex number is normal
397 #[inline]
398 pub fn is_normal(self) -> bool {
399 self.re.is_normal() && self.im.is_normal()
400 }
401 }
402
403 impl<T: Clone + Num> From<T> for Complex<T> {
404 #[inline]
405 fn from(re: T) -> Complex<T> {
406 Complex { re: re, im: T::zero() }
407 }
408 }
409
410 impl<'a, T: Clone + Num> From<&'a T> for Complex<T> {
411 #[inline]
412 fn from(re: &T) -> Complex<T> {
413 From::from(re.clone())
414 }
415 }
416
417 macro_rules! forward_ref_ref_binop {
418 (impl $imp:ident, $method:ident) => {
419 impl<'a, 'b, T: Clone + Num> $imp<&'b Complex<T>> for &'a Complex<T> {
420 type Output = Complex<T>;
421
422 #[inline]
423 fn $method(self, other: &Complex<T>) -> Complex<T> {
424 self.clone().$method(other.clone())
425 }
426 }
427 }
428 }
429
430 macro_rules! forward_ref_val_binop {
431 (impl $imp:ident, $method:ident) => {
432 impl<'a, T: Clone + Num> $imp<Complex<T>> for &'a Complex<T> {
433 type Output = Complex<T>;
434
435 #[inline]
436 fn $method(self, other: Complex<T>) -> Complex<T> {
437 self.clone().$method(other)
438 }
439 }
440 }
441 }
442
443 macro_rules! forward_val_ref_binop {
444 (impl $imp:ident, $method:ident) => {
445 impl<'a, T: Clone + Num> $imp<&'a Complex<T>> for Complex<T> {
446 type Output = Complex<T>;
447
448 #[inline]
449 fn $method(self, other: &Complex<T>) -> Complex<T> {
450 self.$method(other.clone())
451 }
452 }
453 }
454 }
455
456 macro_rules! forward_all_binop {
457 (impl $imp:ident, $method:ident) => {
458 forward_ref_ref_binop!(impl $imp, $method);
459 forward_ref_val_binop!(impl $imp, $method);
460 forward_val_ref_binop!(impl $imp, $method);
461 };
462 }
463
464 /* arithmetic */
465 forward_all_binop!(impl Add, add);
466
467 // (a + i b) + (c + i d) == (a + c) + i (b + d)
468 impl<T: Clone + Num> Add<Complex<T>> for Complex<T> {
469 type Output = Complex<T>;
470
471 #[inline]
472 fn add(self, other: Complex<T>) -> Complex<T> {
473 Complex::new(self.re + other.re, self.im + other.im)
474 }
475 }
476
477 forward_all_binop!(impl Sub, sub);
478
479 // (a + i b) - (c + i d) == (a - c) + i (b - d)
480 impl<T: Clone + Num> Sub<Complex<T>> for Complex<T> {
481 type Output = Complex<T>;
482
483 #[inline]
484 fn sub(self, other: Complex<T>) -> Complex<T> {
485 Complex::new(self.re - other.re, self.im - other.im)
486 }
487 }
488
489 forward_all_binop!(impl Mul, mul);
490
491 // (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c)
492 impl<T: Clone + Num> Mul<Complex<T>> for Complex<T> {
493 type Output = Complex<T>;
494
495 #[inline]
496 fn mul(self, other: Complex<T>) -> Complex<T> {
497 let re = self.re.clone() * other.re.clone() - self.im.clone() * other.im.clone();
498 let im = self.re * other.im + self.im * other.re;
499 Complex::new(re, im)
500 }
501 }
502
503 forward_all_binop!(impl Div, div);
504
505 // (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d)
506 // == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)]
507 impl<T: Clone + Num> Div<Complex<T>> for Complex<T> {
508 type Output = Complex<T>;
509
510 #[inline]
511 fn div(self, other: Complex<T>) -> Complex<T> {
512 let norm_sqr = other.norm_sqr();
513 let re = self.re.clone() * other.re.clone() + self.im.clone() * other.im.clone();
514 let im = self.im * other.re - self.re * other.im;
515 Complex::new(re / norm_sqr.clone(), im / norm_sqr)
516 }
517 }
518
519 impl<T: Clone + Num + Neg<Output = T>> Neg for Complex<T> {
520 type Output = Complex<T>;
521
522 #[inline]
523 fn neg(self) -> Complex<T> {
524 Complex::new(-self.re, -self.im)
525 }
526 }
527
528 impl<'a, T: Clone + Num + Neg<Output = T>> Neg for &'a Complex<T> {
529 type Output = Complex<T>;
530
531 #[inline]
532 fn neg(self) -> Complex<T> {
533 -self.clone()
534 }
535 }
536
537 macro_rules! real_arithmetic {
538 (@forward $imp:ident::$method:ident for $($real:ident),*) => (
539 impl<'a, T: Clone + Num> $imp<&'a T> for Complex<T> {
540 type Output = Complex<T>;
541
542 #[inline]
543 fn $method(self, other: &T) -> Complex<T> {
544 self.$method(other.clone())
545 }
546 }
547 impl<'a, T: Clone + Num> $imp<T> for &'a Complex<T> {
548 type Output = Complex<T>;
549
550 #[inline]
551 fn $method(self, other: T) -> Complex<T> {
552 self.clone().$method(other)
553 }
554 }
555 impl<'a, 'b, T: Clone + Num> $imp<&'a T> for &'b Complex<T> {
556 type Output = Complex<T>;
557
558 #[inline]
559 fn $method(self, other: &T) -> Complex<T> {
560 self.clone().$method(other.clone())
561 }
562 }
563 $(
564 impl<'a> $imp<&'a Complex<$real>> for $real {
565 type Output = Complex<$real>;
566
567 #[inline]
568 fn $method(self, other: &Complex<$real>) -> Complex<$real> {
569 self.$method(other.clone())
570 }
571 }
572 impl<'a> $imp<Complex<$real>> for &'a $real {
573 type Output = Complex<$real>;
574
575 #[inline]
576 fn $method(self, other: Complex<$real>) -> Complex<$real> {
577 self.clone().$method(other)
578 }
579 }
580 impl<'a, 'b> $imp<&'a Complex<$real>> for &'b $real {
581 type Output = Complex<$real>;
582
583 #[inline]
584 fn $method(self, other: &Complex<$real>) -> Complex<$real> {
585 self.clone().$method(other.clone())
586 }
587 }
588 )*
589 );
590 (@implement $imp:ident::$method:ident for $($real:ident),*) => (
591 impl<T: Clone + Num> $imp<T> for Complex<T> {
592 type Output = Complex<T>;
593
594 #[inline]
595 fn $method(self, other: T) -> Complex<T> {
596 self.$method(Complex::from(other))
597 }
598 }
599 $(
600 impl $imp<Complex<$real>> for $real {
601 type Output = Complex<$real>;
602
603 #[inline]
604 fn $method(self, other: Complex<$real>) -> Complex<$real> {
605 Complex::from(self).$method(other)
606 }
607 }
608 )*
609 );
610 ($($real:ident),*) => (
611 real_arithmetic!(@forward Add::add for $($real),*);
612 real_arithmetic!(@forward Sub::sub for $($real),*);
613 real_arithmetic!(@forward Mul::mul for $($real),*);
614 real_arithmetic!(@forward Div::div for $($real),*);
615 real_arithmetic!(@implement Add::add for $($real),*);
616 real_arithmetic!(@implement Sub::sub for $($real),*);
617 real_arithmetic!(@implement Mul::mul for $($real),*);
618 real_arithmetic!(@implement Div::div for $($real),*);
619 );
620 }
621
622 real_arithmetic!(usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64);
623
624 /* constants */
625 impl<T: Clone + Num> Zero for Complex<T> {
626 #[inline]
627 fn zero() -> Complex<T> {
628 Complex::new(Zero::zero(), Zero::zero())
629 }
630
631 #[inline]
632 fn is_zero(&self) -> bool {
633 self.re.is_zero() && self.im.is_zero()
634 }
635 }
636
637 impl<T: Clone + Num> One for Complex<T> {
638 #[inline]
639 fn one() -> Complex<T> {
640 Complex::new(One::one(), Zero::zero())
641 }
642 }
643
644 macro_rules! write_complex {
645 ($f:ident, $t:expr, $prefix:expr, $re:expr, $im:expr, $T:ident) => {{
646 let abs_re = if $re < Zero::zero() { $T::zero() - $re.clone() } else { $re.clone() };
647 let abs_im = if $im < Zero::zero() { $T::zero() - $im.clone() } else { $im.clone() };
648
649 let real: String;
650 let imag: String;
651
652 if let Some(prec) = $f.precision() {
653 real = format!(concat!("{:.1$", $t, "}"), abs_re, prec);
654 imag = format!(concat!("{:.1$", $t, "}"), abs_im, prec);
655 }
656 else {
657 real = format!(concat!("{:", $t, "}"), abs_re);
658 imag = format!(concat!("{:", $t, "}"), abs_im);
659 }
660
661 let prefix = if $f.alternate() { $prefix } else { "" };
662 let sign = if $re < Zero::zero() {
663 "-"
664 } else if $f.sign_plus() {
665 "+"
666 } else {
667 ""
668 };
669
670 let complex = if $im < Zero::zero() {
671 format!("{}{pre}{re}-{pre}{im}i", sign, re=real, im=imag, pre=prefix)
672 }
673 else {
674 format!("{}{pre}{re}+{pre}{im}i", sign, re=real, im=imag, pre=prefix)
675 };
676
677 if let Some(width) = $f.width() {
678 write!($f, "{0: >1$}", complex, width)
679 }
680 else {
681 write!($f, "{}", complex)
682 }
683 }}
684 }
685
686 /* string conversions */
687 impl<T> fmt::Display for Complex<T> where
688 T: fmt::Display + Num + PartialOrd + Clone
689 {
690 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
691 write_complex!(f, "", "", self.re, self.im, T)
692 }
693 }
694
695 impl<T> fmt::LowerExp for Complex<T> where
696 T: fmt::LowerExp + Num + PartialOrd + Clone
697 {
698 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
699 write_complex!(f, "e", "", self.re, self.im, T)
700 }
701 }
702
703 impl<T> fmt::UpperExp for Complex<T> where
704 T: fmt::UpperExp + Num + PartialOrd + Clone
705 {
706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
707 write_complex!(f, "E", "", self.re, self.im, T)
708 }
709 }
710
711 impl<T> fmt::LowerHex for Complex<T> where
712 T: fmt::LowerHex + Num + PartialOrd + Clone
713 {
714 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
715 write_complex!(f, "x", "0x", self.re, self.im, T)
716 }
717 }
718
719 impl<T> fmt::UpperHex for Complex<T> where
720 T: fmt::UpperHex + Num + PartialOrd + Clone
721 {
722 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
723 write_complex!(f, "X", "0x", self.re, self.im, T)
724 }
725 }
726
727 impl<T> fmt::Octal for Complex<T> where
728 T: fmt::Octal + Num + PartialOrd + Clone
729 {
730 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
731 write_complex!(f, "o", "0o", self.re, self.im, T)
732 }
733 }
734
735 impl<T> fmt::Binary for Complex<T> where
736 T: fmt::Binary + Num + PartialOrd + Clone
737 {
738 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
739 write_complex!(f, "b", "0b", self.re, self.im, T)
740 }
741 }
742
743 #[cfg(feature = "serde")]
744 impl<T> serde::Serialize for Complex<T>
745 where T: serde::Serialize
746 {
747 fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where
748 S: serde::Serializer
749 {
750 (&self.re, &self.im).serialize(serializer)
751 }
752 }
753
754 #[cfg(feature = "serde")]
755 impl<T> serde::Deserialize for Complex<T> where
756 T: serde::Deserialize + Num + Clone
757 {
758 fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error> where
759 D: serde::Deserializer,
760 {
761 let (re, im) = try!(serde::Deserialize::deserialize(deserializer));
762 Ok(Complex::new(re, im))
763 }
764 }
765
766 #[cfg(test)]
767 fn hash<T: hash::Hash>(x: &T) -> u64 {
768 use std::hash::Hasher;
769 let mut hasher = hash::SipHasher::new();
770 x.hash(&mut hasher);
771 hasher.finish()
772 }
773
774 #[cfg(test)]
775 mod test {
776 #![allow(non_upper_case_globals)]
777
778 use super::{Complex64, Complex};
779 use std::f64;
780
781 use traits::{Zero, One, Float};
782
783 pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
784 pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
785 pub const _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 };
786 pub const _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 };
787 pub const _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 };
788 pub const _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 };
789 pub const all_consts : [Complex64; 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i];
790
791 #[test]
792 fn test_consts() {
793 // check our constants are what Complex::new creates
794 fn test(c : Complex64, r : f64, i: f64) {
795 assert_eq!(c, Complex::new(r,i));
796 }
797 test(_0_0i, 0.0, 0.0);
798 test(_1_0i, 1.0, 0.0);
799 test(_1_1i, 1.0, 1.0);
800 test(_neg1_1i, -1.0, 1.0);
801 test(_05_05i, 0.5, 0.5);
802
803 assert_eq!(_0_0i, Zero::zero());
804 assert_eq!(_1_0i, One::one());
805 }
806
807 #[test]
808 #[cfg_attr(target_arch = "x86", ignore)]
809 // FIXME #7158: (maybe?) currently failing on x86.
810 fn test_norm() {
811 fn test(c: Complex64, ns: f64) {
812 assert_eq!(c.norm_sqr(), ns);
813 assert_eq!(c.norm(), ns.sqrt())
814 }
815 test(_0_0i, 0.0);
816 test(_1_0i, 1.0);
817 test(_1_1i, 2.0);
818 test(_neg1_1i, 2.0);
819 test(_05_05i, 0.5);
820 }
821
822 #[test]
823 fn test_scale_unscale() {
824 assert_eq!(_05_05i.scale(2.0), _1_1i);
825 assert_eq!(_1_1i.unscale(2.0), _05_05i);
826 for &c in all_consts.iter() {
827 assert_eq!(c.scale(2.0).unscale(2.0), c);
828 }
829 }
830
831 #[test]
832 fn test_conj() {
833 for &c in all_consts.iter() {
834 assert_eq!(c.conj(), Complex::new(c.re, -c.im));
835 assert_eq!(c.conj().conj(), c);
836 }
837 }
838
839 #[test]
840 fn test_inv() {
841 assert_eq!(_1_1i.inv(), _05_05i.conj());
842 assert_eq!(_1_0i.inv(), _1_0i.inv());
843 }
844
845 #[test]
846 #[should_panic]
847 fn test_divide_by_zero_natural() {
848 let n = Complex::new(2, 3);
849 let d = Complex::new(0, 0);
850 let _x = n / d;
851 }
852
853 #[test]
854 fn test_inv_zero() {
855 // FIXME #20: should this really fail, or just NaN?
856 assert!(_0_0i.inv().is_nan());
857 }
858
859 #[test]
860 fn test_arg() {
861 fn test(c: Complex64, arg: f64) {
862 assert!((c.arg() - arg).abs() < 1.0e-6)
863 }
864 test(_1_0i, 0.0);
865 test(_1_1i, 0.25 * f64::consts::PI);
866 test(_neg1_1i, 0.75 * f64::consts::PI);
867 test(_05_05i, 0.25 * f64::consts::PI);
868 }
869
870 #[test]
871 fn test_polar_conv() {
872 fn test(c: Complex64) {
873 let (r, theta) = c.to_polar();
874 assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6);
875 }
876 for &c in all_consts.iter() { test(c); }
877 }
878
879 fn close(a: Complex64, b: Complex64) -> bool {
880 close_to_tol(a, b, 1e-10)
881 }
882
883 fn close_to_tol(a: Complex64, b: Complex64, tol: f64) -> bool {
884 // returns true if a and b are reasonably close
885 (a == b) || (a-b).norm() < tol
886 }
887
888 #[test]
889 fn test_exp() {
890 assert!(close(_1_0i.exp(), _1_0i.scale(f64::consts::E)));
891 assert!(close(_0_0i.exp(), _1_0i));
892 assert!(close(_0_1i.exp(), Complex::new(1.0.cos(), 1.0.sin())));
893 assert!(close(_05_05i.exp()*_05_05i.exp(), _1_1i.exp()));
894 assert!(close(_0_1i.scale(-f64::consts::PI).exp(), _1_0i.scale(-1.0)));
895 for &c in all_consts.iter() {
896 // e^conj(z) = conj(e^z)
897 assert!(close(c.conj().exp(), c.exp().conj()));
898 // e^(z + 2 pi i) = e^z
899 assert!(close(c.exp(), (c + _0_1i.scale(f64::consts::PI*2.0)).exp()));
900 }
901 }
902
903 #[test]
904 fn test_ln() {
905 assert!(close(_1_0i.ln(), _0_0i));
906 assert!(close(_0_1i.ln(), _0_1i.scale(f64::consts::PI/2.0)));
907 assert!(close(_0_0i.ln(), Complex::new(f64::neg_infinity(), 0.0)));
908 assert!(close((_neg1_1i * _05_05i).ln(), _neg1_1i.ln() + _05_05i.ln()));
909 for &c in all_consts.iter() {
910 // ln(conj(z() = conj(ln(z))
911 assert!(close(c.conj().ln(), c.ln().conj()));
912 // for this branch, -pi <= arg(ln(z)) <= pi
913 assert!(-f64::consts::PI <= c.ln().arg() && c.ln().arg() <= f64::consts::PI);
914 }
915 }
916
917 #[test]
918 fn test_powc()
919 {
920 let a = Complex::new(2.0, -3.0);
921 let b = Complex::new(3.0, 0.0);
922 assert!(close(a.powc(b), a.powf(b.re)));
923 assert!(close(b.powc(a), a.expf(b.re)));
924 let c = Complex::new(1.0 / 3.0, 0.1);
925 assert!(close_to_tol(a.powc(c), Complex::new(1.65826, -0.33502), 1e-5));
926 }
927
928 #[test]
929 fn test_powf()
930 {
931 let c = Complex::new(2.0, -1.0);
932 let r = c.powf(3.5);
933 assert!(close_to_tol(r, Complex::new(-0.8684746, -16.695934), 1e-5));
934 }
935
936 #[test]
937 fn test_log()
938 {
939 let c = Complex::new(2.0, -1.0);
940 let r = c.log(10.0);
941 assert!(close_to_tol(r, Complex::new(0.349485, -0.20135958), 1e-5));
942 }
943
944 #[test]
945 fn test_some_expf_cases()
946 {
947 let c = Complex::new(2.0, -1.0);
948 let r = c.expf(10.0);
949 assert!(close_to_tol(r, Complex::new(-66.82015, -74.39803), 1e-5));
950
951 let c = Complex::new(5.0, -2.0);
952 let r = c.expf(3.4);
953 assert!(close_to_tol(r, Complex::new(-349.25, -290.63), 1e-2));
954
955 let c = Complex::new(-1.5, 2.0 / 3.0);
956 let r = c.expf(1.0 / 3.0);
957 assert!(close_to_tol(r, Complex::new(3.8637, -3.4745), 1e-2));
958 }
959
960 #[test]
961 fn test_sqrt() {
962 assert!(close(_0_0i.sqrt(), _0_0i));
963 assert!(close(_1_0i.sqrt(), _1_0i));
964 assert!(close(Complex::new(-1.0, 0.0).sqrt(), _0_1i));
965 assert!(close(Complex::new(-1.0, -0.0).sqrt(), _0_1i.scale(-1.0)));
966 assert!(close(_0_1i.sqrt(), _05_05i.scale(2.0.sqrt())));
967 for &c in all_consts.iter() {
968 // sqrt(conj(z() = conj(sqrt(z))
969 assert!(close(c.conj().sqrt(), c.sqrt().conj()));
970 // for this branch, -pi/2 <= arg(sqrt(z)) <= pi/2
971 assert!(-f64::consts::PI/2.0 <= c.sqrt().arg() && c.sqrt().arg() <= f64::consts::PI/2.0);
972 // sqrt(z) * sqrt(z) = z
973 assert!(close(c.sqrt()*c.sqrt(), c));
974 }
975 }
976
977 #[test]
978 fn test_sin() {
979 assert!(close(_0_0i.sin(), _0_0i));
980 assert!(close(_1_0i.scale(f64::consts::PI*2.0).sin(), _0_0i));
981 assert!(close(_0_1i.sin(), _0_1i.scale(1.0.sinh())));
982 for &c in all_consts.iter() {
983 // sin(conj(z)) = conj(sin(z))
984 assert!(close(c.conj().sin(), c.sin().conj()));
985 // sin(-z) = -sin(z)
986 assert!(close(c.scale(-1.0).sin(), c.sin().scale(-1.0)));
987 }
988 }
989
990 #[test]
991 fn test_cos() {
992 assert!(close(_0_0i.cos(), _1_0i));
993 assert!(close(_1_0i.scale(f64::consts::PI*2.0).cos(), _1_0i));
994 assert!(close(_0_1i.cos(), _1_0i.scale(1.0.cosh())));
995 for &c in all_consts.iter() {
996 // cos(conj(z)) = conj(cos(z))
997 assert!(close(c.conj().cos(), c.cos().conj()));
998 // cos(-z) = cos(z)
999 assert!(close(c.scale(-1.0).cos(), c.cos()));
1000 }
1001 }
1002
1003 #[test]
1004 fn test_tan() {
1005 assert!(close(_0_0i.tan(), _0_0i));
1006 assert!(close(_1_0i.scale(f64::consts::PI/4.0).tan(), _1_0i));
1007 assert!(close(_1_0i.scale(f64::consts::PI).tan(), _0_0i));
1008 for &c in all_consts.iter() {
1009 // tan(conj(z)) = conj(tan(z))
1010 assert!(close(c.conj().tan(), c.tan().conj()));
1011 // tan(-z) = -tan(z)
1012 assert!(close(c.scale(-1.0).tan(), c.tan().scale(-1.0)));
1013 }
1014 }
1015
1016 #[test]
1017 fn test_asin() {
1018 assert!(close(_0_0i.asin(), _0_0i));
1019 assert!(close(_1_0i.asin(), _1_0i.scale(f64::consts::PI/2.0)));
1020 assert!(close(_1_0i.scale(-1.0).asin(), _1_0i.scale(-f64::consts::PI/2.0)));
1021 assert!(close(_0_1i.asin(), _0_1i.scale((1.0 + 2.0.sqrt()).ln())));
1022 for &c in all_consts.iter() {
1023 // asin(conj(z)) = conj(asin(z))
1024 assert!(close(c.conj().asin(), c.asin().conj()));
1025 // asin(-z) = -asin(z)
1026 assert!(close(c.scale(-1.0).asin(), c.asin().scale(-1.0)));
1027 // for this branch, -pi/2 <= asin(z).re <= pi/2
1028 assert!(-f64::consts::PI/2.0 <= c.asin().re && c.asin().re <= f64::consts::PI/2.0);
1029 }
1030 }
1031
1032 #[test]
1033 fn test_acos() {
1034 assert!(close(_0_0i.acos(), _1_0i.scale(f64::consts::PI/2.0)));
1035 assert!(close(_1_0i.acos(), _0_0i));
1036 assert!(close(_1_0i.scale(-1.0).acos(), _1_0i.scale(f64::consts::PI)));
1037 assert!(close(_0_1i.acos(), Complex::new(f64::consts::PI/2.0, (2.0.sqrt() - 1.0).ln())));
1038 for &c in all_consts.iter() {
1039 // acos(conj(z)) = conj(acos(z))
1040 assert!(close(c.conj().acos(), c.acos().conj()));
1041 // for this branch, 0 <= acos(z).re <= pi
1042 assert!(0.0 <= c.acos().re && c.acos().re <= f64::consts::PI);
1043 }
1044 }
1045
1046 #[test]
1047 fn test_atan() {
1048 assert!(close(_0_0i.atan(), _0_0i));
1049 assert!(close(_1_0i.atan(), _1_0i.scale(f64::consts::PI/4.0)));
1050 assert!(close(_1_0i.scale(-1.0).atan(), _1_0i.scale(-f64::consts::PI/4.0)));
1051 assert!(close(_0_1i.atan(), Complex::new(0.0, f64::infinity())));
1052 for &c in all_consts.iter() {
1053 // atan(conj(z)) = conj(atan(z))
1054 assert!(close(c.conj().atan(), c.atan().conj()));
1055 // atan(-z) = -atan(z)
1056 assert!(close(c.scale(-1.0).atan(), c.atan().scale(-1.0)));
1057 // for this branch, -pi/2 <= atan(z).re <= pi/2
1058 assert!(-f64::consts::PI/2.0 <= c.atan().re && c.atan().re <= f64::consts::PI/2.0);
1059 }
1060 }
1061
1062 #[test]
1063 fn test_sinh() {
1064 assert!(close(_0_0i.sinh(), _0_0i));
1065 assert!(close(_1_0i.sinh(), _1_0i.scale((f64::consts::E - 1.0/f64::consts::E)/2.0)));
1066 assert!(close(_0_1i.sinh(), _0_1i.scale(1.0.sin())));
1067 for &c in all_consts.iter() {
1068 // sinh(conj(z)) = conj(sinh(z))
1069 assert!(close(c.conj().sinh(), c.sinh().conj()));
1070 // sinh(-z) = -sinh(z)
1071 assert!(close(c.scale(-1.0).sinh(), c.sinh().scale(-1.0)));
1072 }
1073 }
1074
1075 #[test]
1076 fn test_cosh() {
1077 assert!(close(_0_0i.cosh(), _1_0i));
1078 assert!(close(_1_0i.cosh(), _1_0i.scale((f64::consts::E + 1.0/f64::consts::E)/2.0)));
1079 assert!(close(_0_1i.cosh(), _1_0i.scale(1.0.cos())));
1080 for &c in all_consts.iter() {
1081 // cosh(conj(z)) = conj(cosh(z))
1082 assert!(close(c.conj().cosh(), c.cosh().conj()));
1083 // cosh(-z) = cosh(z)
1084 assert!(close(c.scale(-1.0).cosh(), c.cosh()));
1085 }
1086 }
1087
1088 #[test]
1089 fn test_tanh() {
1090 assert!(close(_0_0i.tanh(), _0_0i));
1091 assert!(close(_1_0i.tanh(), _1_0i.scale((f64::consts::E.powi(2) - 1.0)/(f64::consts::E.powi(2) + 1.0))));
1092 assert!(close(_0_1i.tanh(), _0_1i.scale(1.0.tan())));
1093 for &c in all_consts.iter() {
1094 // tanh(conj(z)) = conj(tanh(z))
1095 assert!(close(c.conj().tanh(), c.conj().tanh()));
1096 // tanh(-z) = -tanh(z)
1097 assert!(close(c.scale(-1.0).tanh(), c.tanh().scale(-1.0)));
1098 }
1099 }
1100
1101 #[test]
1102 fn test_asinh() {
1103 assert!(close(_0_0i.asinh(), _0_0i));
1104 assert!(close(_1_0i.asinh(), _1_0i.scale(1.0 + 2.0.sqrt()).ln()));
1105 assert!(close(_0_1i.asinh(), _0_1i.scale(f64::consts::PI/2.0)));
1106 assert!(close(_0_1i.asinh().scale(-1.0), _0_1i.scale(-f64::consts::PI/2.0)));
1107 for &c in all_consts.iter() {
1108 // asinh(conj(z)) = conj(asinh(z))
1109 assert!(close(c.conj().asinh(), c.conj().asinh()));
1110 // asinh(-z) = -asinh(z)
1111 assert!(close(c.scale(-1.0).asinh(), c.asinh().scale(-1.0)));
1112 // for this branch, -pi/2 <= asinh(z).im <= pi/2
1113 assert!(-f64::consts::PI/2.0 <= c.asinh().im && c.asinh().im <= f64::consts::PI/2.0);
1114 }
1115 }
1116
1117 #[test]
1118 fn test_acosh() {
1119 assert!(close(_0_0i.acosh(), _0_1i.scale(f64::consts::PI/2.0)));
1120 assert!(close(_1_0i.acosh(), _0_0i));
1121 assert!(close(_1_0i.scale(-1.0).acosh(), _0_1i.scale(f64::consts::PI)));
1122 for &c in all_consts.iter() {
1123 // acosh(conj(z)) = conj(acosh(z))
1124 assert!(close(c.conj().acosh(), c.conj().acosh()));
1125 // for this branch, -pi <= acosh(z).im <= pi and 0 <= acosh(z).re
1126 assert!(-f64::consts::PI <= c.acosh().im && c.acosh().im <= f64::consts::PI && 0.0 <= c.cosh().re);
1127 }
1128 }
1129
1130 #[test]
1131 fn test_atanh() {
1132 assert!(close(_0_0i.atanh(), _0_0i));
1133 assert!(close(_0_1i.atanh(), _0_1i.scale(f64::consts::PI/4.0)));
1134 assert!(close(_1_0i.atanh(), Complex::new(f64::infinity(), 0.0)));
1135 for &c in all_consts.iter() {
1136 // atanh(conj(z)) = conj(atanh(z))
1137 assert!(close(c.conj().atanh(), c.conj().atanh()));
1138 // atanh(-z) = -atanh(z)
1139 assert!(close(c.scale(-1.0).atanh(), c.atanh().scale(-1.0)));
1140 // for this branch, -pi/2 <= atanh(z).im <= pi/2
1141 assert!(-f64::consts::PI/2.0 <= c.atanh().im && c.atanh().im <= f64::consts::PI/2.0);
1142 }
1143 }
1144
1145 #[test]
1146 fn test_exp_ln() {
1147 for &c in all_consts.iter() {
1148 // e^ln(z) = z
1149 assert!(close(c.ln().exp(), c));
1150 }
1151 }
1152
1153 #[test]
1154 fn test_trig_to_hyperbolic() {
1155 for &c in all_consts.iter() {
1156 // sin(iz) = i sinh(z)
1157 assert!(close((_0_1i * c).sin(), _0_1i * c.sinh()));
1158 // cos(iz) = cosh(z)
1159 assert!(close((_0_1i * c).cos(), c.cosh()));
1160 // tan(iz) = i tanh(z)
1161 assert!(close((_0_1i * c).tan(), _0_1i * c.tanh()));
1162 }
1163 }
1164
1165 #[test]
1166 fn test_trig_identities() {
1167 for &c in all_consts.iter() {
1168 // tan(z) = sin(z)/cos(z)
1169 assert!(close(c.tan(), c.sin()/c.cos()));
1170 // sin(z)^2 + cos(z)^2 = 1
1171 assert!(close(c.sin()*c.sin() + c.cos()*c.cos(), _1_0i));
1172
1173 // sin(asin(z)) = z
1174 assert!(close(c.asin().sin(), c));
1175 // cos(acos(z)) = z
1176 assert!(close(c.acos().cos(), c));
1177 // tan(atan(z)) = z
1178 // i and -i are branch points
1179 if c != _0_1i && c != _0_1i.scale(-1.0) {
1180 assert!(close(c.atan().tan(), c));
1181 }
1182
1183 // sin(z) = (e^(iz) - e^(-iz))/(2i)
1184 assert!(close(((_0_1i*c).exp() - (_0_1i*c).exp().inv())/_0_1i.scale(2.0), c.sin()));
1185 // cos(z) = (e^(iz) + e^(-iz))/2
1186 assert!(close(((_0_1i*c).exp() + (_0_1i*c).exp().inv()).unscale(2.0), c.cos()));
1187 // tan(z) = i (1 - e^(2iz))/(1 + e^(2iz))
1188 assert!(close(_0_1i * (_1_0i - (_0_1i*c).scale(2.0).exp())/(_1_0i + (_0_1i*c).scale(2.0).exp()), c.tan()));
1189 }
1190 }
1191
1192 #[test]
1193 fn test_hyperbolic_identites() {
1194 for &c in all_consts.iter() {
1195 // tanh(z) = sinh(z)/cosh(z)
1196 assert!(close(c.tanh(), c.sinh()/c.cosh()));
1197 // cosh(z)^2 - sinh(z)^2 = 1
1198 assert!(close(c.cosh()*c.cosh() - c.sinh()*c.sinh(), _1_0i));
1199
1200 // sinh(asinh(z)) = z
1201 assert!(close(c.asinh().sinh(), c));
1202 // cosh(acosh(z)) = z
1203 assert!(close(c.acosh().cosh(), c));
1204 // tanh(atanh(z)) = z
1205 // 1 and -1 are branch points
1206 if c != _1_0i && c != _1_0i.scale(-1.0) {
1207 assert!(close(c.atanh().tanh(), c));
1208 }
1209
1210 // sinh(z) = (e^z - e^(-z))/2
1211 assert!(close((c.exp() - c.exp().inv()).unscale(2.0), c.sinh()));
1212 // cosh(z) = (e^z + e^(-z))/2
1213 assert!(close((c.exp() + c.exp().inv()).unscale(2.0), c.cosh()));
1214 // tanh(z) = ( e^(2z) - 1)/(e^(2z) + 1)
1215 assert!(close((c.scale(2.0).exp() - _1_0i)/(c.scale(2.0).exp() + _1_0i), c.tanh()));
1216 }
1217 }
1218
1219 mod complex_arithmetic {
1220 use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts};
1221 use traits::Zero;
1222
1223 #[test]
1224 fn test_add() {
1225 assert_eq!(_05_05i + _05_05i, _1_1i);
1226 assert_eq!(_0_1i + _1_0i, _1_1i);
1227 assert_eq!(_1_0i + _neg1_1i, _0_1i);
1228
1229 for &c in all_consts.iter() {
1230 assert_eq!(_0_0i + c, c);
1231 assert_eq!(c + _0_0i, c);
1232 }
1233 }
1234
1235 #[test]
1236 fn test_sub() {
1237 assert_eq!(_05_05i - _05_05i, _0_0i);
1238 assert_eq!(_0_1i - _1_0i, _neg1_1i);
1239 assert_eq!(_0_1i - _neg1_1i, _1_0i);
1240
1241 for &c in all_consts.iter() {
1242 assert_eq!(c - _0_0i, c);
1243 assert_eq!(c - c, _0_0i);
1244 }
1245 }
1246
1247 #[test]
1248 fn test_mul() {
1249 assert_eq!(_05_05i * _05_05i, _0_1i.unscale(2.0));
1250 assert_eq!(_1_1i * _0_1i, _neg1_1i);
1251
1252 // i^2 & i^4
1253 assert_eq!(_0_1i * _0_1i, -_1_0i);
1254 assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i);
1255
1256 for &c in all_consts.iter() {
1257 assert_eq!(c * _1_0i, c);
1258 assert_eq!(_1_0i * c, c);
1259 }
1260 }
1261
1262 #[test]
1263 fn test_div() {
1264 assert_eq!(_neg1_1i / _0_1i, _1_1i);
1265 for &c in all_consts.iter() {
1266 if c != Zero::zero() {
1267 assert_eq!(c / c, _1_0i);
1268 }
1269 }
1270 }
1271
1272 #[test]
1273 fn test_neg() {
1274 assert_eq!(-_1_0i + _0_1i, _neg1_1i);
1275 assert_eq!((-_0_1i) * _0_1i, _1_0i);
1276 for &c in all_consts.iter() {
1277 assert_eq!(-(-c), c);
1278 }
1279 }
1280 }
1281
1282 mod real_arithmetic {
1283 use super::super::Complex;
1284
1285 #[test]
1286 fn test_add() {
1287 assert_eq!(Complex::new(4.0, 2.0) + 0.5, Complex::new(4.5, 2.0));
1288 assert_eq!(0.5 + Complex::new(4.0, 2.0), Complex::new(4.5, 2.0));
1289 }
1290
1291 #[test]
1292 fn test_sub() {
1293 assert_eq!(Complex::new(4.0, 2.0) - 0.5, Complex::new(3.5, 2.0));
1294 assert_eq!(0.5 - Complex::new(4.0, 2.0), Complex::new(-3.5, -2.0));
1295 }
1296
1297 #[test]
1298 fn test_mul() {
1299 assert_eq!(Complex::new(4.0, 2.0) * 0.5, Complex::new(2.0, 1.0));
1300 assert_eq!(0.5 * Complex::new(4.0, 2.0), Complex::new(2.0, 1.0));
1301 }
1302
1303 #[test]
1304 fn test_div() {
1305 assert_eq!(Complex::new(4.0, 2.0) / 0.5, Complex::new(8.0, 4.0));
1306 assert_eq!(0.5 / Complex::new(4.0, 2.0), Complex::new(0.1, -0.05));
1307 }
1308 }
1309
1310 #[test]
1311 fn test_to_string() {
1312 fn test(c : Complex64, s: String) {
1313 assert_eq!(c.to_string(), s);
1314 }
1315 test(_0_0i, "0+0i".to_string());
1316 test(_1_0i, "1+0i".to_string());
1317 test(_0_1i, "0+1i".to_string());
1318 test(_1_1i, "1+1i".to_string());
1319 test(_neg1_1i, "-1+1i".to_string());
1320 test(-_neg1_1i, "1-1i".to_string());
1321 test(_05_05i, "0.5+0.5i".to_string());
1322 }
1323
1324 #[test]
1325 fn test_string_formatting() {
1326 let a = Complex::new(1.23456, 123.456);
1327 assert_eq!(format!("{}", a), "1.23456+123.456i");
1328 assert_eq!(format!("{:.2}", a), "1.23+123.46i");
1329 assert_eq!(format!("{:.2e}", a), "1.23e0+1.23e2i");
1330 assert_eq!(format!("{:+20.2E}", a), " +1.23E0+1.23E2i");
1331
1332 let b = Complex::new(0x80, 0xff);
1333 assert_eq!(format!("{:X}", b), "80+FFi");
1334 assert_eq!(format!("{:#x}", b), "0x80+0xffi");
1335 assert_eq!(format!("{:+#b}", b), "+0b10000000+0b11111111i");
1336 assert_eq!(format!("{:+#16o}", b), " +0o200+0o377i");
1337
1338 let c = Complex::new(-10, -10000);
1339 assert_eq!(format!("{}", c), "-10-10000i");
1340 assert_eq!(format!("{:16}", c), " -10-10000i");
1341 }
1342
1343 #[test]
1344 fn test_hash() {
1345 let a = Complex::new(0i32, 0i32);
1346 let b = Complex::new(1i32, 0i32);
1347 let c = Complex::new(0i32, 1i32);
1348 assert!(::hash(&a) != ::hash(&b));
1349 assert!(::hash(&b) != ::hash(&c));
1350 assert!(::hash(&c) != ::hash(&a));
1351 }
1352
1353 #[test]
1354 fn test_hashset() {
1355 use std::collections::HashSet;
1356 let a = Complex::new(0i32, 0i32);
1357 let b = Complex::new(1i32, 0i32);
1358 let c = Complex::new(0i32, 1i32);
1359
1360 let set: HashSet<_> = [a, b, c].iter().cloned().collect();
1361 assert!(set.contains(&a));
1362 assert!(set.contains(&b));
1363 assert!(set.contains(&c));
1364 assert!(!set.contains(&(a + b + c)));
1365 }
1366
1367 #[test]
1368 fn test_is_nan() {
1369 assert!(!_1_1i.is_nan());
1370 let a = Complex::new(f64::NAN, f64::NAN);
1371 assert!(a.is_nan());
1372 }
1373
1374 #[test]
1375 fn test_is_nan_special_cases() {
1376 let a = Complex::new(0f64, f64::NAN);
1377 let b = Complex::new(f64::NAN, 0f64);
1378 assert!(a.is_nan());
1379 assert!(b.is_nan());
1380 }
1381
1382 #[test]
1383 fn test_is_infinite() {
1384 let a = Complex::new(2f64, f64::INFINITY);
1385 assert!(a.is_infinite());
1386 }
1387
1388 #[test]
1389 fn test_is_finite() {
1390 assert!(_1_1i.is_finite())
1391 }
1392
1393 #[test]
1394 fn test_is_normal() {
1395 let a = Complex::new(0f64, f64::NAN);
1396 let b = Complex::new(2f64, f64::INFINITY);
1397 assert!(!a.is_normal());
1398 assert!(!b.is_normal());
1399 assert!(_1_1i.is_normal());
1400 }
1401 }