lib.rs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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. /* string conversions */
  541. impl<T> fmt::Display for Complex<T> where
  542. T: fmt::Display + Num + PartialOrd + Clone
  543. {
  544. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  545. if self.im < Zero::zero() {
  546. write!(f, "{}-{}i", self.re, T::zero() - self.im.clone())
  547. } else {
  548. write!(f, "{}+{}i", self.re, self.im)
  549. }
  550. }
  551. }
  552. #[cfg(feature = "serde")]
  553. impl<T> serde::Serialize for Complex<T>
  554. where T: serde::Serialize
  555. {
  556. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where
  557. S: serde::Serializer
  558. {
  559. (&self.re, &self.im).serialize(serializer)
  560. }
  561. }
  562. #[cfg(feature = "serde")]
  563. impl<T> serde::Deserialize for Complex<T> where
  564. T: serde::Deserialize + Num + Clone
  565. {
  566. fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error> where
  567. D: serde::Deserializer,
  568. {
  569. let (re, im) = try!(serde::Deserialize::deserialize(deserializer));
  570. Ok(Complex::new(re, im))
  571. }
  572. }
  573. #[cfg(test)]
  574. fn hash<T: hash::Hash>(x: &T) -> u64 {
  575. use std::hash::Hasher;
  576. let mut hasher = hash::SipHasher::new();
  577. x.hash(&mut hasher);
  578. hasher.finish()
  579. }
  580. #[cfg(test)]
  581. mod test {
  582. #![allow(non_upper_case_globals)]
  583. use super::{Complex64, Complex};
  584. use std::f64;
  585. use traits::{Zero, One, Float};
  586. pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
  587. pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
  588. pub const _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 };
  589. pub const _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 };
  590. pub const _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 };
  591. pub const _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 };
  592. pub const all_consts : [Complex64; 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i];
  593. #[test]
  594. fn test_consts() {
  595. // check our constants are what Complex::new creates
  596. fn test(c : Complex64, r : f64, i: f64) {
  597. assert_eq!(c, Complex::new(r,i));
  598. }
  599. test(_0_0i, 0.0, 0.0);
  600. test(_1_0i, 1.0, 0.0);
  601. test(_1_1i, 1.0, 1.0);
  602. test(_neg1_1i, -1.0, 1.0);
  603. test(_05_05i, 0.5, 0.5);
  604. assert_eq!(_0_0i, Zero::zero());
  605. assert_eq!(_1_0i, One::one());
  606. }
  607. #[test]
  608. #[cfg_attr(target_arch = "x86", ignore)]
  609. // FIXME #7158: (maybe?) currently failing on x86.
  610. fn test_norm() {
  611. fn test(c: Complex64, ns: f64) {
  612. assert_eq!(c.norm_sqr(), ns);
  613. assert_eq!(c.norm(), ns.sqrt())
  614. }
  615. test(_0_0i, 0.0);
  616. test(_1_0i, 1.0);
  617. test(_1_1i, 2.0);
  618. test(_neg1_1i, 2.0);
  619. test(_05_05i, 0.5);
  620. }
  621. #[test]
  622. fn test_scale_unscale() {
  623. assert_eq!(_05_05i.scale(2.0), _1_1i);
  624. assert_eq!(_1_1i.unscale(2.0), _05_05i);
  625. for &c in all_consts.iter() {
  626. assert_eq!(c.scale(2.0).unscale(2.0), c);
  627. }
  628. }
  629. #[test]
  630. fn test_conj() {
  631. for &c in all_consts.iter() {
  632. assert_eq!(c.conj(), Complex::new(c.re, -c.im));
  633. assert_eq!(c.conj().conj(), c);
  634. }
  635. }
  636. #[test]
  637. fn test_inv() {
  638. assert_eq!(_1_1i.inv(), _05_05i.conj());
  639. assert_eq!(_1_0i.inv(), _1_0i.inv());
  640. }
  641. #[test]
  642. #[should_panic]
  643. fn test_divide_by_zero_natural() {
  644. let n = Complex::new(2, 3);
  645. let d = Complex::new(0, 0);
  646. let _x = n / d;
  647. }
  648. #[test]
  649. fn test_inv_zero() {
  650. // FIXME #20: should this really fail, or just NaN?
  651. assert!(_0_0i.inv().is_nan());
  652. }
  653. #[test]
  654. fn test_arg() {
  655. fn test(c: Complex64, arg: f64) {
  656. assert!((c.arg() - arg).abs() < 1.0e-6)
  657. }
  658. test(_1_0i, 0.0);
  659. test(_1_1i, 0.25 * f64::consts::PI);
  660. test(_neg1_1i, 0.75 * f64::consts::PI);
  661. test(_05_05i, 0.25 * f64::consts::PI);
  662. }
  663. #[test]
  664. fn test_polar_conv() {
  665. fn test(c: Complex64) {
  666. let (r, theta) = c.to_polar();
  667. assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6);
  668. }
  669. for &c in all_consts.iter() { test(c); }
  670. }
  671. fn close(a: Complex64, b: Complex64) -> bool {
  672. close_to_tol(a, b, 1e-10)
  673. }
  674. fn close_to_tol(a: Complex64, b: Complex64, tol: f64) -> bool {
  675. // returns true if a and b are reasonably close
  676. (a == b) || (a-b).norm() < tol
  677. }
  678. #[test]
  679. fn test_exp() {
  680. assert!(close(_1_0i.exp(), _1_0i.scale(f64::consts::E)));
  681. assert!(close(_0_0i.exp(), _1_0i));
  682. assert!(close(_0_1i.exp(), Complex::new(1.0.cos(), 1.0.sin())));
  683. assert!(close(_05_05i.exp()*_05_05i.exp(), _1_1i.exp()));
  684. assert!(close(_0_1i.scale(-f64::consts::PI).exp(), _1_0i.scale(-1.0)));
  685. for &c in all_consts.iter() {
  686. // e^conj(z) = conj(e^z)
  687. assert!(close(c.conj().exp(), c.exp().conj()));
  688. // e^(z + 2 pi i) = e^z
  689. assert!(close(c.exp(), (c + _0_1i.scale(f64::consts::PI*2.0)).exp()));
  690. }
  691. }
  692. #[test]
  693. fn test_ln() {
  694. assert!(close(_1_0i.ln(), _0_0i));
  695. assert!(close(_0_1i.ln(), _0_1i.scale(f64::consts::PI/2.0)));
  696. assert!(close(_0_0i.ln(), Complex::new(f64::neg_infinity(), 0.0)));
  697. assert!(close((_neg1_1i * _05_05i).ln(), _neg1_1i.ln() + _05_05i.ln()));
  698. for &c in all_consts.iter() {
  699. // ln(conj(z() = conj(ln(z))
  700. assert!(close(c.conj().ln(), c.ln().conj()));
  701. // for this branch, -pi <= arg(ln(z)) <= pi
  702. assert!(-f64::consts::PI <= c.ln().arg() && c.ln().arg() <= f64::consts::PI);
  703. }
  704. }
  705. #[test]
  706. fn test_powc()
  707. {
  708. let a = Complex::new(2.0, -3.0);
  709. let b = Complex::new(3.0, 0.0);
  710. assert!(close(a.powc(b), a.powf(b.re)));
  711. assert!(close(b.powc(a), a.expf(b.re)));
  712. let c = Complex::new(1.0 / 3.0, 0.1);
  713. assert!(close_to_tol(a.powc(c), Complex::new(1.65826, -0.33502), 1e-5));
  714. }
  715. #[test]
  716. fn test_powf()
  717. {
  718. let c = Complex::new(2.0, -1.0);
  719. let r = c.powf(3.5);
  720. assert!(close_to_tol(r, Complex::new(-0.8684746, -16.695934), 1e-5));
  721. }
  722. #[test]
  723. fn test_log()
  724. {
  725. let c = Complex::new(2.0, -1.0);
  726. let r = c.log(10.0);
  727. assert!(close_to_tol(r, Complex::new(0.349485, -0.20135958), 1e-5));
  728. }
  729. #[test]
  730. fn test_some_expf_cases()
  731. {
  732. let c = Complex::new(2.0, -1.0);
  733. let r = c.expf(10.0);
  734. assert!(close_to_tol(r, Complex::new(-66.82015, -74.39803), 1e-5));
  735. let c = Complex::new(5.0, -2.0);
  736. let r = c.expf(3.4);
  737. assert!(close_to_tol(r, Complex::new(-349.25, -290.63), 1e-2));
  738. let c = Complex::new(-1.5, 2.0 / 3.0);
  739. let r = c.expf(1.0 / 3.0);
  740. assert!(close_to_tol(r, Complex::new(3.8637, -3.4745), 1e-2));
  741. }
  742. #[test]
  743. fn test_sqrt() {
  744. assert!(close(_0_0i.sqrt(), _0_0i));
  745. assert!(close(_1_0i.sqrt(), _1_0i));
  746. assert!(close(Complex::new(-1.0, 0.0).sqrt(), _0_1i));
  747. assert!(close(Complex::new(-1.0, -0.0).sqrt(), _0_1i.scale(-1.0)));
  748. assert!(close(_0_1i.sqrt(), _05_05i.scale(2.0.sqrt())));
  749. for &c in all_consts.iter() {
  750. // sqrt(conj(z() = conj(sqrt(z))
  751. assert!(close(c.conj().sqrt(), c.sqrt().conj()));
  752. // for this branch, -pi/2 <= arg(sqrt(z)) <= pi/2
  753. assert!(-f64::consts::PI/2.0 <= c.sqrt().arg() && c.sqrt().arg() <= f64::consts::PI/2.0);
  754. // sqrt(z) * sqrt(z) = z
  755. assert!(close(c.sqrt()*c.sqrt(), c));
  756. }
  757. }
  758. #[test]
  759. fn test_sin() {
  760. assert!(close(_0_0i.sin(), _0_0i));
  761. assert!(close(_1_0i.scale(f64::consts::PI*2.0).sin(), _0_0i));
  762. assert!(close(_0_1i.sin(), _0_1i.scale(1.0.sinh())));
  763. for &c in all_consts.iter() {
  764. // sin(conj(z)) = conj(sin(z))
  765. assert!(close(c.conj().sin(), c.sin().conj()));
  766. // sin(-z) = -sin(z)
  767. assert!(close(c.scale(-1.0).sin(), c.sin().scale(-1.0)));
  768. }
  769. }
  770. #[test]
  771. fn test_cos() {
  772. assert!(close(_0_0i.cos(), _1_0i));
  773. assert!(close(_1_0i.scale(f64::consts::PI*2.0).cos(), _1_0i));
  774. assert!(close(_0_1i.cos(), _1_0i.scale(1.0.cosh())));
  775. for &c in all_consts.iter() {
  776. // cos(conj(z)) = conj(cos(z))
  777. assert!(close(c.conj().cos(), c.cos().conj()));
  778. // cos(-z) = cos(z)
  779. assert!(close(c.scale(-1.0).cos(), c.cos()));
  780. }
  781. }
  782. #[test]
  783. fn test_tan() {
  784. assert!(close(_0_0i.tan(), _0_0i));
  785. assert!(close(_1_0i.scale(f64::consts::PI/4.0).tan(), _1_0i));
  786. assert!(close(_1_0i.scale(f64::consts::PI).tan(), _0_0i));
  787. for &c in all_consts.iter() {
  788. // tan(conj(z)) = conj(tan(z))
  789. assert!(close(c.conj().tan(), c.tan().conj()));
  790. // tan(-z) = -tan(z)
  791. assert!(close(c.scale(-1.0).tan(), c.tan().scale(-1.0)));
  792. }
  793. }
  794. #[test]
  795. fn test_asin() {
  796. assert!(close(_0_0i.asin(), _0_0i));
  797. assert!(close(_1_0i.asin(), _1_0i.scale(f64::consts::PI/2.0)));
  798. assert!(close(_1_0i.scale(-1.0).asin(), _1_0i.scale(-f64::consts::PI/2.0)));
  799. assert!(close(_0_1i.asin(), _0_1i.scale((1.0 + 2.0.sqrt()).ln())));
  800. for &c in all_consts.iter() {
  801. // asin(conj(z)) = conj(asin(z))
  802. assert!(close(c.conj().asin(), c.asin().conj()));
  803. // asin(-z) = -asin(z)
  804. assert!(close(c.scale(-1.0).asin(), c.asin().scale(-1.0)));
  805. // for this branch, -pi/2 <= asin(z).re <= pi/2
  806. assert!(-f64::consts::PI/2.0 <= c.asin().re && c.asin().re <= f64::consts::PI/2.0);
  807. }
  808. }
  809. #[test]
  810. fn test_acos() {
  811. assert!(close(_0_0i.acos(), _1_0i.scale(f64::consts::PI/2.0)));
  812. assert!(close(_1_0i.acos(), _0_0i));
  813. assert!(close(_1_0i.scale(-1.0).acos(), _1_0i.scale(f64::consts::PI)));
  814. assert!(close(_0_1i.acos(), Complex::new(f64::consts::PI/2.0, (2.0.sqrt() - 1.0).ln())));
  815. for &c in all_consts.iter() {
  816. // acos(conj(z)) = conj(acos(z))
  817. assert!(close(c.conj().acos(), c.acos().conj()));
  818. // for this branch, 0 <= acos(z).re <= pi
  819. assert!(0.0 <= c.acos().re && c.acos().re <= f64::consts::PI);
  820. }
  821. }
  822. #[test]
  823. fn test_atan() {
  824. assert!(close(_0_0i.atan(), _0_0i));
  825. assert!(close(_1_0i.atan(), _1_0i.scale(f64::consts::PI/4.0)));
  826. assert!(close(_1_0i.scale(-1.0).atan(), _1_0i.scale(-f64::consts::PI/4.0)));
  827. assert!(close(_0_1i.atan(), Complex::new(0.0, f64::infinity())));
  828. for &c in all_consts.iter() {
  829. // atan(conj(z)) = conj(atan(z))
  830. assert!(close(c.conj().atan(), c.atan().conj()));
  831. // atan(-z) = -atan(z)
  832. assert!(close(c.scale(-1.0).atan(), c.atan().scale(-1.0)));
  833. // for this branch, -pi/2 <= atan(z).re <= pi/2
  834. assert!(-f64::consts::PI/2.0 <= c.atan().re && c.atan().re <= f64::consts::PI/2.0);
  835. }
  836. }
  837. #[test]
  838. fn test_sinh() {
  839. assert!(close(_0_0i.sinh(), _0_0i));
  840. assert!(close(_1_0i.sinh(), _1_0i.scale((f64::consts::E - 1.0/f64::consts::E)/2.0)));
  841. assert!(close(_0_1i.sinh(), _0_1i.scale(1.0.sin())));
  842. for &c in all_consts.iter() {
  843. // sinh(conj(z)) = conj(sinh(z))
  844. assert!(close(c.conj().sinh(), c.sinh().conj()));
  845. // sinh(-z) = -sinh(z)
  846. assert!(close(c.scale(-1.0).sinh(), c.sinh().scale(-1.0)));
  847. }
  848. }
  849. #[test]
  850. fn test_cosh() {
  851. assert!(close(_0_0i.cosh(), _1_0i));
  852. assert!(close(_1_0i.cosh(), _1_0i.scale((f64::consts::E + 1.0/f64::consts::E)/2.0)));
  853. assert!(close(_0_1i.cosh(), _1_0i.scale(1.0.cos())));
  854. for &c in all_consts.iter() {
  855. // cosh(conj(z)) = conj(cosh(z))
  856. assert!(close(c.conj().cosh(), c.cosh().conj()));
  857. // cosh(-z) = cosh(z)
  858. assert!(close(c.scale(-1.0).cosh(), c.cosh()));
  859. }
  860. }
  861. #[test]
  862. fn test_tanh() {
  863. assert!(close(_0_0i.tanh(), _0_0i));
  864. assert!(close(_1_0i.tanh(), _1_0i.scale((f64::consts::E.powi(2) - 1.0)/(f64::consts::E.powi(2) + 1.0))));
  865. assert!(close(_0_1i.tanh(), _0_1i.scale(1.0.tan())));
  866. for &c in all_consts.iter() {
  867. // tanh(conj(z)) = conj(tanh(z))
  868. assert!(close(c.conj().tanh(), c.conj().tanh()));
  869. // tanh(-z) = -tanh(z)
  870. assert!(close(c.scale(-1.0).tanh(), c.tanh().scale(-1.0)));
  871. }
  872. }
  873. #[test]
  874. fn test_asinh() {
  875. assert!(close(_0_0i.asinh(), _0_0i));
  876. assert!(close(_1_0i.asinh(), _1_0i.scale(1.0 + 2.0.sqrt()).ln()));
  877. assert!(close(_0_1i.asinh(), _0_1i.scale(f64::consts::PI/2.0)));
  878. assert!(close(_0_1i.asinh().scale(-1.0), _0_1i.scale(-f64::consts::PI/2.0)));
  879. for &c in all_consts.iter() {
  880. // asinh(conj(z)) = conj(asinh(z))
  881. assert!(close(c.conj().asinh(), c.conj().asinh()));
  882. // asinh(-z) = -asinh(z)
  883. assert!(close(c.scale(-1.0).asinh(), c.asinh().scale(-1.0)));
  884. // for this branch, -pi/2 <= asinh(z).im <= pi/2
  885. assert!(-f64::consts::PI/2.0 <= c.asinh().im && c.asinh().im <= f64::consts::PI/2.0);
  886. }
  887. }
  888. #[test]
  889. fn test_acosh() {
  890. assert!(close(_0_0i.acosh(), _0_1i.scale(f64::consts::PI/2.0)));
  891. assert!(close(_1_0i.acosh(), _0_0i));
  892. assert!(close(_1_0i.scale(-1.0).acosh(), _0_1i.scale(f64::consts::PI)));
  893. for &c in all_consts.iter() {
  894. // acosh(conj(z)) = conj(acosh(z))
  895. assert!(close(c.conj().acosh(), c.conj().acosh()));
  896. // for this branch, -pi <= acosh(z).im <= pi and 0 <= acosh(z).re
  897. assert!(-f64::consts::PI <= c.acosh().im && c.acosh().im <= f64::consts::PI && 0.0 <= c.cosh().re);
  898. }
  899. }
  900. #[test]
  901. fn test_atanh() {
  902. assert!(close(_0_0i.atanh(), _0_0i));
  903. assert!(close(_0_1i.atanh(), _0_1i.scale(f64::consts::PI/4.0)));
  904. assert!(close(_1_0i.atanh(), Complex::new(f64::infinity(), 0.0)));
  905. for &c in all_consts.iter() {
  906. // atanh(conj(z)) = conj(atanh(z))
  907. assert!(close(c.conj().atanh(), c.conj().atanh()));
  908. // atanh(-z) = -atanh(z)
  909. assert!(close(c.scale(-1.0).atanh(), c.atanh().scale(-1.0)));
  910. // for this branch, -pi/2 <= atanh(z).im <= pi/2
  911. assert!(-f64::consts::PI/2.0 <= c.atanh().im && c.atanh().im <= f64::consts::PI/2.0);
  912. }
  913. }
  914. #[test]
  915. fn test_exp_ln() {
  916. for &c in all_consts.iter() {
  917. // e^ln(z) = z
  918. assert!(close(c.ln().exp(), c));
  919. }
  920. }
  921. #[test]
  922. fn test_trig_to_hyperbolic() {
  923. for &c in all_consts.iter() {
  924. // sin(iz) = i sinh(z)
  925. assert!(close((_0_1i * c).sin(), _0_1i * c.sinh()));
  926. // cos(iz) = cosh(z)
  927. assert!(close((_0_1i * c).cos(), c.cosh()));
  928. // tan(iz) = i tanh(z)
  929. assert!(close((_0_1i * c).tan(), _0_1i * c.tanh()));
  930. }
  931. }
  932. #[test]
  933. fn test_trig_identities() {
  934. for &c in all_consts.iter() {
  935. // tan(z) = sin(z)/cos(z)
  936. assert!(close(c.tan(), c.sin()/c.cos()));
  937. // sin(z)^2 + cos(z)^2 = 1
  938. assert!(close(c.sin()*c.sin() + c.cos()*c.cos(), _1_0i));
  939. // sin(asin(z)) = z
  940. assert!(close(c.asin().sin(), c));
  941. // cos(acos(z)) = z
  942. assert!(close(c.acos().cos(), c));
  943. // tan(atan(z)) = z
  944. // i and -i are branch points
  945. if c != _0_1i && c != _0_1i.scale(-1.0) {
  946. assert!(close(c.atan().tan(), c));
  947. }
  948. // sin(z) = (e^(iz) - e^(-iz))/(2i)
  949. assert!(close(((_0_1i*c).exp() - (_0_1i*c).exp().inv())/_0_1i.scale(2.0), c.sin()));
  950. // cos(z) = (e^(iz) + e^(-iz))/2
  951. assert!(close(((_0_1i*c).exp() + (_0_1i*c).exp().inv()).unscale(2.0), c.cos()));
  952. // tan(z) = i (1 - e^(2iz))/(1 + e^(2iz))
  953. assert!(close(_0_1i * (_1_0i - (_0_1i*c).scale(2.0).exp())/(_1_0i + (_0_1i*c).scale(2.0).exp()), c.tan()));
  954. }
  955. }
  956. #[test]
  957. fn test_hyperbolic_identites() {
  958. for &c in all_consts.iter() {
  959. // tanh(z) = sinh(z)/cosh(z)
  960. assert!(close(c.tanh(), c.sinh()/c.cosh()));
  961. // cosh(z)^2 - sinh(z)^2 = 1
  962. assert!(close(c.cosh()*c.cosh() - c.sinh()*c.sinh(), _1_0i));
  963. // sinh(asinh(z)) = z
  964. assert!(close(c.asinh().sinh(), c));
  965. // cosh(acosh(z)) = z
  966. assert!(close(c.acosh().cosh(), c));
  967. // tanh(atanh(z)) = z
  968. // 1 and -1 are branch points
  969. if c != _1_0i && c != _1_0i.scale(-1.0) {
  970. assert!(close(c.atanh().tanh(), c));
  971. }
  972. // sinh(z) = (e^z - e^(-z))/2
  973. assert!(close((c.exp() - c.exp().inv()).unscale(2.0), c.sinh()));
  974. // cosh(z) = (e^z + e^(-z))/2
  975. assert!(close((c.exp() + c.exp().inv()).unscale(2.0), c.cosh()));
  976. // tanh(z) = ( e^(2z) - 1)/(e^(2z) + 1)
  977. assert!(close((c.scale(2.0).exp() - _1_0i)/(c.scale(2.0).exp() + _1_0i), c.tanh()));
  978. }
  979. }
  980. mod complex_arithmetic {
  981. use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts};
  982. use traits::Zero;
  983. #[test]
  984. fn test_add() {
  985. assert_eq!(_05_05i + _05_05i, _1_1i);
  986. assert_eq!(_0_1i + _1_0i, _1_1i);
  987. assert_eq!(_1_0i + _neg1_1i, _0_1i);
  988. for &c in all_consts.iter() {
  989. assert_eq!(_0_0i + c, c);
  990. assert_eq!(c + _0_0i, c);
  991. }
  992. }
  993. #[test]
  994. fn test_sub() {
  995. assert_eq!(_05_05i - _05_05i, _0_0i);
  996. assert_eq!(_0_1i - _1_0i, _neg1_1i);
  997. assert_eq!(_0_1i - _neg1_1i, _1_0i);
  998. for &c in all_consts.iter() {
  999. assert_eq!(c - _0_0i, c);
  1000. assert_eq!(c - c, _0_0i);
  1001. }
  1002. }
  1003. #[test]
  1004. fn test_mul() {
  1005. assert_eq!(_05_05i * _05_05i, _0_1i.unscale(2.0));
  1006. assert_eq!(_1_1i * _0_1i, _neg1_1i);
  1007. // i^2 & i^4
  1008. assert_eq!(_0_1i * _0_1i, -_1_0i);
  1009. assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i);
  1010. for &c in all_consts.iter() {
  1011. assert_eq!(c * _1_0i, c);
  1012. assert_eq!(_1_0i * c, c);
  1013. }
  1014. }
  1015. #[test]
  1016. fn test_div() {
  1017. assert_eq!(_neg1_1i / _0_1i, _1_1i);
  1018. for &c in all_consts.iter() {
  1019. if c != Zero::zero() {
  1020. assert_eq!(c / c, _1_0i);
  1021. }
  1022. }
  1023. }
  1024. #[test]
  1025. fn test_neg() {
  1026. assert_eq!(-_1_0i + _0_1i, _neg1_1i);
  1027. assert_eq!((-_0_1i) * _0_1i, _1_0i);
  1028. for &c in all_consts.iter() {
  1029. assert_eq!(-(-c), c);
  1030. }
  1031. }
  1032. }
  1033. mod real_arithmetic {
  1034. use super::super::Complex;
  1035. #[test]
  1036. fn test_add() {
  1037. assert_eq!(Complex::new(4.0, 2.0) + 0.5, Complex::new(4.5, 2.0));
  1038. assert_eq!(0.5 + Complex::new(4.0, 2.0), Complex::new(4.5, 2.0));
  1039. }
  1040. #[test]
  1041. fn test_sub() {
  1042. assert_eq!(Complex::new(4.0, 2.0) - 0.5, Complex::new(3.5, 2.0));
  1043. assert_eq!(0.5 - Complex::new(4.0, 2.0), Complex::new(-3.5, -2.0));
  1044. }
  1045. #[test]
  1046. fn test_mul() {
  1047. assert_eq!(Complex::new(4.0, 2.0) * 0.5, Complex::new(2.0, 1.0));
  1048. assert_eq!(0.5 * Complex::new(4.0, 2.0), Complex::new(2.0, 1.0));
  1049. }
  1050. #[test]
  1051. fn test_div() {
  1052. assert_eq!(Complex::new(4.0, 2.0) / 0.5, Complex::new(8.0, 4.0));
  1053. assert_eq!(0.5 / Complex::new(4.0, 2.0), Complex::new(0.1, -0.05));
  1054. }
  1055. }
  1056. #[test]
  1057. fn test_to_string() {
  1058. fn test(c : Complex64, s: String) {
  1059. assert_eq!(c.to_string(), s);
  1060. }
  1061. test(_0_0i, "0+0i".to_string());
  1062. test(_1_0i, "1+0i".to_string());
  1063. test(_0_1i, "0+1i".to_string());
  1064. test(_1_1i, "1+1i".to_string());
  1065. test(_neg1_1i, "-1+1i".to_string());
  1066. test(-_neg1_1i, "1-1i".to_string());
  1067. test(_05_05i, "0.5+0.5i".to_string());
  1068. }
  1069. #[test]
  1070. fn test_hash() {
  1071. let a = Complex::new(0i32, 0i32);
  1072. let b = Complex::new(1i32, 0i32);
  1073. let c = Complex::new(0i32, 1i32);
  1074. assert!(::hash(&a) != ::hash(&b));
  1075. assert!(::hash(&b) != ::hash(&c));
  1076. assert!(::hash(&c) != ::hash(&a));
  1077. }
  1078. #[test]
  1079. fn test_hashset() {
  1080. use std::collections::HashSet;
  1081. let a = Complex::new(0i32, 0i32);
  1082. let b = Complex::new(1i32, 0i32);
  1083. let c = Complex::new(0i32, 1i32);
  1084. let set: HashSet<_> = [a, b, c].iter().cloned().collect();
  1085. assert!(set.contains(&a));
  1086. assert!(set.contains(&b));
  1087. assert!(set.contains(&c));
  1088. assert!(!set.contains(&(a + b + c)));
  1089. }
  1090. #[test]
  1091. fn test_is_nan() {
  1092. assert!(!_1_1i.is_nan());
  1093. let a = Complex::new(f64::NAN, f64::NAN);
  1094. assert!(a.is_nan());
  1095. }
  1096. #[test]
  1097. fn test_is_nan_special_cases() {
  1098. let a = Complex::new(0f64, f64::NAN);
  1099. let b = Complex::new(f64::NAN, 0f64);
  1100. assert!(a.is_nan());
  1101. assert!(b.is_nan());
  1102. }
  1103. #[test]
  1104. fn test_is_infinite() {
  1105. let a = Complex::new(2f64, f64::INFINITY);
  1106. assert!(a.is_infinite());
  1107. }
  1108. #[test]
  1109. fn test_is_finite() {
  1110. assert!(_1_1i.is_finite())
  1111. }
  1112. #[test]
  1113. fn test_is_normal() {
  1114. let a = Complex::new(0f64, f64::NAN);
  1115. let b = Complex::new(2f64, f64::INFINITY);
  1116. assert!(!a.is_normal());
  1117. assert!(!b.is_normal());
  1118. assert!(_1_1i.is_normal());
  1119. }
  1120. }