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.
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/")]
17 extern crate num_traits
as traits
;
19 #[cfg(feature = "rustc-serialize")]
20 extern crate rustc_serialize
;
22 #[cfg(feature = "serde")]
28 use std
::ops
::{Add, Div, Mul, Neg, Sub}
;
30 use traits
::{Zero, One, Num, Float}
;
32 // FIXME #1284: handle complex NaN & infinity etc. This
33 // probably doesn't map to C's _Complex correctly.
35 /// A complex number in Cartesian form.
37 /// ## Representation and Foreign Function Interface Compatibility
39 /// `Complex<T>` is memory layout compatible with an array `[T; 2]`.
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.
48 /// Example of extern function declaration.
51 /// use num_complex::Complex;
52 /// use std::os::raw::c_int;
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);
60 #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default)]
61 #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
63 pub struct Complex
<T
> {
64 /// Real portion of the complex number
66 /// Imaginary portion of the complex number
70 pub type Complex32
= Complex
<f32>;
71 pub type Complex64
= Complex
<f64>;
73 impl<T
: Clone
+ Num
> Complex
<T
> {
74 /// Create a new Complex
76 pub fn new(re
: T
, im
: T
) -> Complex
<T
> {
77 Complex { re: re, im: im }
80 /// Returns imaginary unit
82 pub fn i() -> Complex
<T
> {
83 Self::new(T
::zero(), T
::one())
86 /// Returns the square of the norm (since `T` doesn't necessarily
87 /// have a sqrt function), i.e. `re^2 + im^2`.
89 pub fn norm_sqr(&self) -> T
{
90 self.re
.clone() * self.re
.clone() + self.im
.clone() * self.im
.clone()
93 /// Multiplies `self` by the scalar `t`.
95 pub fn scale(&self, t
: T
) -> Complex
<T
> {
96 Complex
::new(self.re
.clone() * t
.clone(), self.im
.clone() * t
)
99 /// Divides `self` by the scalar `t`.
101 pub fn unscale(&self, t
: T
) -> Complex
<T
> {
102 Complex
::new(self.re
.clone() / t
.clone(), self.im
.clone() / t
)
106 impl<T
: Clone
+ Num
+ Neg
<Output
= T
>> Complex
<T
> {
107 /// Returns the complex conjugate. i.e. `re - i im`
109 pub fn conj(&self) -> Complex
<T
> {
110 Complex
::new(self.re
.clone(), -self.im
.clone())
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
)
122 impl<T
: Clone
+ Float
> Complex
<T
> {
125 pub fn norm(&self) -> T
{
126 self.re
.hypot(self.im
)
128 /// Calculate the principal Arg of self.
130 pub fn arg(&self) -> T
{
131 self.im
.atan2(self.re
)
133 /// Convert to polar form (r, theta), such that `self = r * exp(i
136 pub fn to_polar(&self) -> (T
, T
) {
137 (self.norm(), self.arg())
139 /// Convert a polar representation into a complex number.
141 pub fn from_polar(r
: &T
, theta
: &T
) -> Complex
<T
> {
142 Complex
::new(*r
* theta
.cos(), *r
* theta
.sin())
145 /// Computes `e^(self)`, where `e` is the base of the natural logarithm.
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
)
153 /// Computes the principal value of natural logarithm of `self`.
155 /// This function has one branch cut:
157 /// * `(-∞, 0]`, continuous from above.
159 /// The branch satisfies `-π ≤ arg(ln(z)) ≤ π`.
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
)
167 /// Computes the principal value of the square root of `self`.
169 /// This function has one branch cut:
171 /// * `(-∞, 0)`, continuous from above.
173 /// The branch satisfies `-π/2 ≤ arg(sqrt(z)) ≤ π/2`.
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
))
182 /// Raises `self` to a floating point power.
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
))
191 /// Returns the logarithm of `self` with respect to an arbitrary base.
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())
201 /// Raises `self` to a complex power.
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(ρ)))
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();
217 &(r
.powf(exp
.re
) * (-exp
.im
* theta
).exp()),
218 &(exp
.re
* theta
+ exp
.im
* r
.ln()))
221 /// Raises a floating point number to the complex power `self`.
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()))
229 /// Computes the sine of `self`.
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())
236 /// Computes the cosine of `self`.
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())
243 /// Computes the tangent of `self`.
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())
251 /// Computes the principal value of the inverse sine of `self`.
253 /// This function has two branch cuts:
255 /// * `(-∞, -1)`, continuous from above.
256 /// * `(1, ∞)`, continuous from below.
258 /// The branch satisfies `-π/2 ≤ Re(asin(z)) ≤ π/2`.
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()
266 /// Computes the principal value of the inverse cosine of `self`.
268 /// This function has two branch cuts:
270 /// * `(-∞, -1)`, continuous from above.
271 /// * `(1, ∞)`, continuous from below.
273 /// The branch satisfies `0 ≤ Re(acos(z)) ≤ π`.
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()
281 /// Computes the principal value of the inverse tangent of `self`.
283 /// This function has two branch cuts:
285 /// * `(-∞i, -i]`, continuous from the left.
286 /// * `[i, ∞i)`, continuous from the right.
288 /// The branch satisfies `-π/2 ≤ Re(atan(z)) ≤ π/2`.
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();
296 return Complex
::new(T
::zero(), T
::infinity());
298 else if *self == -i
{
299 return Complex
::new(T
::zero(), -T
::infinity());
301 ((one
+ i
* self).ln() - (one
- i
* self).ln()) / (two
* i
)
304 /// Computes the hyperbolic sine of `self`.
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())
311 /// Computes the hyperbolic cosine of `self`.
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())
318 /// Computes the hyperbolic tangent of `self`.
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())
326 /// Computes the principal value of inverse hyperbolic sine of `self`.
328 /// This function has two branch cuts:
330 /// * `(-∞i, -i)`, continuous from the left.
331 /// * `(i, ∞i)`, continuous from the right.
333 /// The branch satisfies `-π/2 ≤ Im(asinh(z)) ≤ π/2`.
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()
341 /// Computes the principal value of inverse hyperbolic cosine of `self`.
343 /// This function has one branch cut:
345 /// * `(-∞, 1)`, continuous from above.
347 /// The branch satisfies `-π ≤ Im(acosh(z)) ≤ π` and `0 ≤ Re(acosh(z)) < ∞`.
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();
353 two
* (((self + one
)/two
).sqrt() + ((self - one
)/two
).sqrt()).ln()
356 /// Computes the principal value of inverse hyperbolic tangent of `self`.
358 /// This function has two branch cuts:
360 /// * `(-∞, -1]`, continuous from above.
361 /// * `[1, ∞)`, continuous from below.
363 /// The branch satisfies `-π/2 ≤ Im(atanh(z)) ≤ π/2`.
365 pub fn atanh(&self) -> Complex
<T
> {
366 // formula: arctanh(z) = (ln(1+z) - ln(1-z))/2
367 let one
= Complex
::one();
370 return Complex
::new(T
::infinity(), T
::zero());
372 else if *self == -one
{
373 return Complex
::new(-T
::infinity(), T
::zero());
375 ((one
+ self).ln() - (one
- self).ln()) / two
378 /// Checks if the given complex number is NaN
380 pub fn is_nan(self) -> bool
{
381 self.re
.is_nan() || self.im
.is_nan()
384 /// Checks if the given complex number is infinite
386 pub fn is_infinite(self) -> bool
{
387 !self.is_nan() && (self.re
.is_infinite() || self.im
.is_infinite())
390 /// Checks if the given complex number is finite
392 pub fn is_finite(self) -> bool
{
393 self.re
.is_finite() && self.im
.is_finite()
396 /// Checks if the given complex number is normal
398 pub fn is_normal(self) -> bool
{
399 self.re
.is_normal() && self.im
.is_normal()
403 impl<T
: Clone
+ Num
> From
<T
> for Complex
<T
> {
405 fn from(re
: T
) -> Complex
<T
> {
406 Complex { re: re, im: T::zero() }
410 impl<'a
, T
: Clone
+ Num
> From
<&'a T
> for Complex
<T
> {
412 fn from(re
: &T
) -> Complex
<T
> {
413 From
::from(re
.clone())
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
>;
423 fn $
method(self, other
: &Complex
<T
>) -> Complex
<T
> {
424 self.clone().$
method(other
.clone())
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
>;
436 fn $
method(self, other
: Complex
<T
>) -> Complex
<T
> {
437 self.clone().$
method(other
)
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
>;
449 fn $
method(self, other
: &Complex
<T
>) -> Complex
<T
> {
450 self.$
method(other
.clone())
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
);
465 forward_all_binop
!(impl Add
, add
);
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
>;
472 fn add(self, other
: Complex
<T
>) -> Complex
<T
> {
473 Complex
::new(self.re
+ other
.re
, self.im
+ other
.im
)
477 forward_all_binop
!(impl Sub
, sub
);
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
>;
484 fn sub(self, other
: Complex
<T
>) -> Complex
<T
> {
485 Complex
::new(self.re
- other
.re
, self.im
- other
.im
)
489 forward_all_binop
!(impl Mul
, mul
);
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
>;
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
;
503 forward_all_binop
!(impl Div
, div
);
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
>;
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
)
519 impl<T
: Clone
+ Num
+ Neg
<Output
= T
>> Neg
for Complex
<T
> {
520 type Output
= Complex
<T
>;
523 fn neg(self) -> Complex
<T
> {
524 Complex
::new(-self.re
, -self.im
)
528 impl<'a
, T
: Clone
+ Num
+ Neg
<Output
= T
>> Neg
for &'a Complex
<T
> {
529 type Output
= Complex
<T
>;
532 fn neg(self) -> Complex
<T
> {
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
>;
543 fn $
method(self, other
: &T
) -> Complex
<T
> {
544 self.$
method(other
.clone())
547 impl<'a
, T
: Clone
+ Num
> $imp
<T
> for &'a Complex
<T
> {
548 type Output
= Complex
<T
>;
551 fn $
method(self, other
: T
) -> Complex
<T
> {
552 self.clone().$
method(other
)
555 impl<'a
, 'b
, T
: Clone
+ Num
> $imp
<&'a T
> for &'b Complex
<T
> {
556 type Output
= Complex
<T
>;
559 fn $
method(self, other
: &T
) -> Complex
<T
> {
560 self.clone().$
method(other
.clone())
564 impl<'a
> $imp
<&'a Complex
<$real
>> for $real
{
565 type Output
= Complex
<$real
>;
568 fn $
method(self, other
: &Complex
<$real
>) -> Complex
<$real
> {
569 self.$
method(other
.clone())
572 impl<'a
> $imp
<Complex
<$real
>> for &'a $real
{
573 type Output
= Complex
<$real
>;
576 fn $
method(self, other
: Complex
<$real
>) -> Complex
<$real
> {
577 self.clone().$
method(other
)
580 impl<'a
, 'b
> $imp
<&'a Complex
<$real
>> for &'b $real
{
581 type Output
= Complex
<$real
>;
584 fn $
method(self, other
: &Complex
<$real
>) -> Complex
<$real
> {
585 self.clone().$
method(other
.clone())
590 (@implement $imp
:ident
::$method
:ident
for $
($real
:ident
),*) => (
591 impl<T
: Clone
+ Num
> $imp
<T
> for Complex
<T
> {
592 type Output
= Complex
<T
>;
595 fn $
method(self, other
: T
) -> Complex
<T
> {
596 self.$
method(Complex
::from(other
))
600 impl $imp
<Complex
<$real
>> for $real
{
601 type Output
= Complex
<$real
>;
604 fn $
method(self, other
: Complex
<$real
>) -> Complex
<$real
> {
605 Complex
::from(self).$
method(other
)
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
),*);
622 real_arithmetic
!(usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64);
625 impl<T
: Clone
+ Num
> Zero
for Complex
<T
> {
627 fn zero() -> Complex
<T
> {
628 Complex
::new(Zero
::zero(), Zero
::zero())
632 fn is_zero(&self) -> bool
{
633 self.re
.is_zero() && self.im
.is_zero()
637 impl<T
: Clone
+ Num
> One
for Complex
<T
> {
639 fn one() -> Complex
<T
> {
640 Complex
::new(One
::one(), Zero
::zero())
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() }
;
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
);
657 real
= format
!(concat
!("{:", $t, "}"), abs_re
);
658 imag
= format
!(concat
!("{:", $t, "}"), abs_im
);
661 let prefix
= if $f
.alternate() { $prefix }
else { "" }
;
662 let sign
= if $re
< Zero
::zero() {
664 } else if $f
.sign_plus() {
670 let complex
= if $im
< Zero
::zero() {
671 format
!("{}{pre}{re}-{pre}{im}i", sign
, re
=real
, im
=imag
, pre
=prefix
)
674 format
!("{}{pre}{re}+{pre}{im}i", sign
, re
=real
, im
=imag
, pre
=prefix
)
677 if let Some(width
) = $f
.width() {
678 write
!($f
, "{0: >1$}", complex
, width
)
681 write
!($f
, "{}", complex
)
686 /* string conversions */
687 impl<T
> fmt
::Display
for Complex
<T
> where
688 T
: fmt
::Display
+ Num
+ PartialOrd
+ Clone
690 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
691 write_complex
!(f
, "", "", self.re
, self.im
, T
)
695 impl<T
> fmt
::LowerExp
for Complex
<T
> where
696 T
: fmt
::LowerExp
+ Num
+ PartialOrd
+ Clone
698 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
699 write_complex
!(f
, "e", "", self.re
, self.im
, T
)
703 impl<T
> fmt
::UpperExp
for Complex
<T
> where
704 T
: fmt
::UpperExp
+ Num
+ PartialOrd
+ Clone
706 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
707 write_complex
!(f
, "E", "", self.re
, self.im
, T
)
711 impl<T
> fmt
::LowerHex
for Complex
<T
> where
712 T
: fmt
::LowerHex
+ Num
+ PartialOrd
+ Clone
714 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
715 write_complex
!(f
, "x", "0x", self.re
, self.im
, T
)
719 impl<T
> fmt
::UpperHex
for Complex
<T
> where
720 T
: fmt
::UpperHex
+ Num
+ PartialOrd
+ Clone
722 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
723 write_complex
!(f
, "X", "0x", self.re
, self.im
, T
)
727 impl<T
> fmt
::Octal
for Complex
<T
> where
728 T
: fmt
::Octal
+ Num
+ PartialOrd
+ Clone
730 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
731 write_complex
!(f
, "o", "0o", self.re
, self.im
, T
)
735 impl<T
> fmt
::Binary
for Complex
<T
> where
736 T
: fmt
::Binary
+ Num
+ PartialOrd
+ Clone
738 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
739 write_complex
!(f
, "b", "0b", self.re
, self.im
, T
)
743 #[cfg(feature = "serde")]
744 impl<T
> serde
::Serialize
for Complex
<T
>
745 where T
: serde
::Serialize
747 fn serialize
<S
>(&self, serializer
: &mut S
) -> Result
<(), S
::Error
> where
750 (&self.re
, &self.im
).serialize(serializer
)
754 #[cfg(feature = "serde")]
755 impl<T
> serde
::Deserialize
for Complex
<T
> where
756 T
: serde
::Deserialize
+ Num
+ Clone
758 fn deserialize
<D
>(deserializer
: &mut D
) -> Result
<Self, D
::Error
> where
759 D
: serde
::Deserializer
,
761 let (re
, im
) = try
!(serde
::Deserialize
::deserialize(deserializer
));
762 Ok(Complex
::new(re
, im
))
767 fn hash
<T
: hash
::Hash
>(x
: &T
) -> u64 {
768 use std
::hash
::Hasher
;
769 let mut hasher
= hash
::SipHasher
::new();
776 #![allow(non_upper_case_globals)]
778 use super::{Complex64, Complex}
;
781 use traits
::{Zero, One, Float}
;
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
];
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
));
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);
803 assert_eq
!(_0_0i
, Zero
::zero());
804 assert_eq
!(_1_0i
, One
::one());
808 #[cfg_attr(target_arch = "x86", ignore)]
809 // FIXME #7158: (maybe?) currently failing on x86.
811 fn test(c
: Complex64
, ns
: f64) {
812 assert_eq
!(c
.norm_sqr(), ns
);
813 assert_eq
!(c
.norm(), ns
.sqrt())
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
);
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
);
841 assert_eq
!(_1_1i
.inv(), _05_05i
.conj());
842 assert_eq
!(_1_0i
.inv(), _1_0i
.inv());
847 fn test_divide_by_zero_natural() {
848 let n
= Complex
::new(2, 3);
849 let d
= Complex
::new(0, 0);
855 // FIXME #20: should this really fail, or just NaN?
856 assert
!(_0_0i
.inv().is_nan());
861 fn test(c
: Complex64
, arg
: f64) {
862 assert
!((c
.arg() - arg
).abs() < 1.0e-6)
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
);
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);
876 for &c
in all_consts
.iter() { test(c); }
879 fn close(a
: Complex64
, b
: Complex64
) -> bool
{
880 close_to_tol(a
, b
, 1e
-10)
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
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()));
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
);
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));
931 let c
= Complex
::new(2.0, -1.0);
933 assert
!(close_to_tol(r
, Complex
::new(-0.8684746, -16.695934), 1e
-5));
939 let c
= Complex
::new(2.0, -1.0);
941 assert
!(close_to_tol(r
, Complex
::new(0.349485, -0.20135958), 1e
-5));
945 fn test_some_expf_cases()
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));
951 let c
= Complex
::new(5.0, -2.0);
953 assert
!(close_to_tol(r
, Complex
::new(-349.25, -290.63), 1e
-2));
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));
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
));
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()));
986 assert
!(close(c
.scale(-1.0).sin(), c
.sin().scale(-1.0)));
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()));
999 assert
!(close(c
.scale(-1.0).cos(), c
.cos()));
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)));
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);
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
);
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);
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)));
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()));
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)));
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);
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
);
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);
1147 for &c
in all_consts
.iter() {
1149 assert
!(close(c
.ln().exp(), c
));
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()));
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
));
1174 assert
!(close(c
.asin().sin(), c
));
1176 assert
!(close(c
.acos().cos(), c
));
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
));
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()));
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
));
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
));
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()));
1219 mod complex_arithmetic
{
1220 use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts}
;
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
);
1229 for &c
in all_consts
.iter() {
1230 assert_eq
!(_0_0i
+ c
, c
);
1231 assert_eq
!(c
+ _0_0i
, c
);
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
);
1241 for &c
in all_consts
.iter() {
1242 assert_eq
!(c
- _0_0i
, c
);
1243 assert_eq
!(c
- c
, _0_0i
);
1249 assert_eq
!(_05_05i
* _05_05i
, _0_1i
.unscale(2.0));
1250 assert_eq
!(_1_1i
* _0_1i
, _neg1_1i
);
1253 assert_eq
!(_0_1i
* _0_1i
, -_1_0i
);
1254 assert_eq
!(_0_1i
* _0_1i
* _0_1i
* _0_1i
, _1_0i
);
1256 for &c
in all_consts
.iter() {
1257 assert_eq
!(c
* _1_0i
, c
);
1258 assert_eq
!(_1_0i
* c
, c
);
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
);
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
);
1282 mod real_arithmetic
{
1283 use super::super::Complex
;
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));
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));
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));
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));
1311 fn test_to_string() {
1312 fn test(c
: Complex64
, s
: String
) {
1313 assert_eq
!(c
.to_string(), s
);
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());
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");
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");
1338 let c
= Complex
::new(-10, -10000);
1339 assert_eq
!(format
!("{}", c
), "-10-10000i");
1340 assert_eq
!(format
!("{:16}", c
), " -10-10000i");
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
));
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);
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
)));
1369 assert
!(!_1_1i
.is_nan());
1370 let a
= Complex
::new(f64::NAN
, f64::NAN
);
1371 assert
!(a
.is_nan());
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());
1383 fn test_is_infinite() {
1384 let a
= Complex
::new(2f64, f64::INFINITY
);
1385 assert
!(a
.is_infinite());
1389 fn test_is_finite() {
1390 assert
!(_1_1i
.is_finite())
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());