lib.rs 44 KB

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