lib.rs 58 KB

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