lib.rs 40 KB

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