float.rs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. use std::mem;
  2. use std::ops::Neg;
  3. use std::num::FpCategory;
  4. // Used for default implementation of `epsilon`
  5. use std::f32;
  6. use {Num, NumCast};
  7. // FIXME: these doctests aren't actually helpful, because they're using and
  8. // testing the inherent methods directly, not going through `Float`.
  9. pub trait Float
  10. : Num
  11. + Copy
  12. + NumCast
  13. + PartialOrd
  14. + Neg<Output = Self>
  15. {
  16. /// Returns the `NaN` value.
  17. ///
  18. /// ```
  19. /// use num_traits::Float;
  20. ///
  21. /// let nan: f32 = Float::nan();
  22. ///
  23. /// assert!(nan.is_nan());
  24. /// ```
  25. fn nan() -> Self;
  26. /// Returns the infinite value.
  27. ///
  28. /// ```
  29. /// use num_traits::Float;
  30. /// use std::f32;
  31. ///
  32. /// let infinity: f32 = Float::infinity();
  33. ///
  34. /// assert!(infinity.is_infinite());
  35. /// assert!(!infinity.is_finite());
  36. /// assert!(infinity > f32::MAX);
  37. /// ```
  38. fn infinity() -> Self;
  39. /// Returns the negative infinite value.
  40. ///
  41. /// ```
  42. /// use num_traits::Float;
  43. /// use std::f32;
  44. ///
  45. /// let neg_infinity: f32 = Float::neg_infinity();
  46. ///
  47. /// assert!(neg_infinity.is_infinite());
  48. /// assert!(!neg_infinity.is_finite());
  49. /// assert!(neg_infinity < f32::MIN);
  50. /// ```
  51. fn neg_infinity() -> Self;
  52. /// Returns `-0.0`.
  53. ///
  54. /// ```
  55. /// use num_traits::{Zero, Float};
  56. ///
  57. /// let inf: f32 = Float::infinity();
  58. /// let zero: f32 = Zero::zero();
  59. /// let neg_zero: f32 = Float::neg_zero();
  60. ///
  61. /// assert_eq!(zero, neg_zero);
  62. /// assert_eq!(7.0f32/inf, zero);
  63. /// assert_eq!(zero * 10.0, zero);
  64. /// ```
  65. fn neg_zero() -> Self;
  66. /// Returns the smallest finite value that this type can represent.
  67. ///
  68. /// ```
  69. /// use num_traits::Float;
  70. /// use std::f64;
  71. ///
  72. /// let x: f64 = Float::min_value();
  73. ///
  74. /// assert_eq!(x, f64::MIN);
  75. /// ```
  76. fn min_value() -> Self;
  77. /// Returns the smallest positive, normalized value that this type can represent.
  78. ///
  79. /// ```
  80. /// use num_traits::Float;
  81. /// use std::f64;
  82. ///
  83. /// let x: f64 = Float::min_positive_value();
  84. ///
  85. /// assert_eq!(x, f64::MIN_POSITIVE);
  86. /// ```
  87. fn min_positive_value() -> Self;
  88. /// Returns epsilon, a small positive value.
  89. ///
  90. /// ```
  91. /// use num_traits::Float;
  92. /// use std::f64;
  93. ///
  94. /// let x: f64 = Float::epsilon();
  95. ///
  96. /// assert_eq!(x, f64::EPSILON);
  97. /// ```
  98. ///
  99. /// # Panics
  100. ///
  101. /// The default implementation will panic if `f32::EPSILON` cannot
  102. /// be cast to `Self`.
  103. fn epsilon() -> Self {
  104. Self::from(f32::EPSILON).expect("Unable to cast from f32::EPSILON")
  105. }
  106. /// Returns the largest finite value that this type can represent.
  107. ///
  108. /// ```
  109. /// use num_traits::Float;
  110. /// use std::f64;
  111. ///
  112. /// let x: f64 = Float::max_value();
  113. /// assert_eq!(x, f64::MAX);
  114. /// ```
  115. fn max_value() -> Self;
  116. /// Returns `true` if this value is `NaN` and false otherwise.
  117. ///
  118. /// ```
  119. /// use num_traits::Float;
  120. /// use std::f64;
  121. ///
  122. /// let nan = f64::NAN;
  123. /// let f = 7.0;
  124. ///
  125. /// assert!(nan.is_nan());
  126. /// assert!(!f.is_nan());
  127. /// ```
  128. fn is_nan(self) -> bool;
  129. /// Returns `true` if this value is positive infinity or negative infinity and
  130. /// false otherwise.
  131. ///
  132. /// ```
  133. /// use num_traits::Float;
  134. /// use std::f32;
  135. ///
  136. /// let f = 7.0f32;
  137. /// let inf: f32 = Float::infinity();
  138. /// let neg_inf: f32 = Float::neg_infinity();
  139. /// let nan: f32 = f32::NAN;
  140. ///
  141. /// assert!(!f.is_infinite());
  142. /// assert!(!nan.is_infinite());
  143. ///
  144. /// assert!(inf.is_infinite());
  145. /// assert!(neg_inf.is_infinite());
  146. /// ```
  147. fn is_infinite(self) -> bool;
  148. /// Returns `true` if this number is neither infinite nor `NaN`.
  149. ///
  150. /// ```
  151. /// use num_traits::Float;
  152. /// use std::f32;
  153. ///
  154. /// let f = 7.0f32;
  155. /// let inf: f32 = Float::infinity();
  156. /// let neg_inf: f32 = Float::neg_infinity();
  157. /// let nan: f32 = f32::NAN;
  158. ///
  159. /// assert!(f.is_finite());
  160. ///
  161. /// assert!(!nan.is_finite());
  162. /// assert!(!inf.is_finite());
  163. /// assert!(!neg_inf.is_finite());
  164. /// ```
  165. fn is_finite(self) -> bool;
  166. /// Returns `true` if the number is neither zero, infinite,
  167. /// [subnormal][subnormal], or `NaN`.
  168. ///
  169. /// ```
  170. /// use num_traits::Float;
  171. /// use std::f32;
  172. ///
  173. /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
  174. /// let max = f32::MAX;
  175. /// let lower_than_min = 1.0e-40_f32;
  176. /// let zero = 0.0f32;
  177. ///
  178. /// assert!(min.is_normal());
  179. /// assert!(max.is_normal());
  180. ///
  181. /// assert!(!zero.is_normal());
  182. /// assert!(!f32::NAN.is_normal());
  183. /// assert!(!f32::INFINITY.is_normal());
  184. /// // Values between `0` and `min` are Subnormal.
  185. /// assert!(!lower_than_min.is_normal());
  186. /// ```
  187. /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number
  188. fn is_normal(self) -> bool;
  189. /// Returns the floating point category of the number. If only one property
  190. /// is going to be tested, it is generally faster to use the specific
  191. /// predicate instead.
  192. ///
  193. /// ```
  194. /// use num_traits::Float;
  195. /// use std::num::FpCategory;
  196. /// use std::f32;
  197. ///
  198. /// let num = 12.4f32;
  199. /// let inf = f32::INFINITY;
  200. ///
  201. /// assert_eq!(num.classify(), FpCategory::Normal);
  202. /// assert_eq!(inf.classify(), FpCategory::Infinite);
  203. /// ```
  204. fn classify(self) -> FpCategory;
  205. /// Returns the largest integer less than or equal to a number.
  206. ///
  207. /// ```
  208. /// use num_traits::Float;
  209. ///
  210. /// let f = 3.99;
  211. /// let g = 3.0;
  212. ///
  213. /// assert_eq!(f.floor(), 3.0);
  214. /// assert_eq!(g.floor(), 3.0);
  215. /// ```
  216. fn floor(self) -> Self;
  217. /// Returns the smallest integer greater than or equal to a number.
  218. ///
  219. /// ```
  220. /// use num_traits::Float;
  221. ///
  222. /// let f = 3.01;
  223. /// let g = 4.0;
  224. ///
  225. /// assert_eq!(f.ceil(), 4.0);
  226. /// assert_eq!(g.ceil(), 4.0);
  227. /// ```
  228. fn ceil(self) -> Self;
  229. /// Returns the nearest integer to a number. Round half-way cases away from
  230. /// `0.0`.
  231. ///
  232. /// ```
  233. /// use num_traits::Float;
  234. ///
  235. /// let f = 3.3;
  236. /// let g = -3.3;
  237. ///
  238. /// assert_eq!(f.round(), 3.0);
  239. /// assert_eq!(g.round(), -3.0);
  240. /// ```
  241. fn round(self) -> Self;
  242. /// Return the integer part of a number.
  243. ///
  244. /// ```
  245. /// use num_traits::Float;
  246. ///
  247. /// let f = 3.3;
  248. /// let g = -3.7;
  249. ///
  250. /// assert_eq!(f.trunc(), 3.0);
  251. /// assert_eq!(g.trunc(), -3.0);
  252. /// ```
  253. fn trunc(self) -> Self;
  254. /// Returns the fractional part of a number.
  255. ///
  256. /// ```
  257. /// use num_traits::Float;
  258. ///
  259. /// let x = 3.5;
  260. /// let y = -3.5;
  261. /// let abs_difference_x = (x.fract() - 0.5).abs();
  262. /// let abs_difference_y = (y.fract() - (-0.5)).abs();
  263. ///
  264. /// assert!(abs_difference_x < 1e-10);
  265. /// assert!(abs_difference_y < 1e-10);
  266. /// ```
  267. fn fract(self) -> Self;
  268. /// Computes the absolute value of `self`. Returns `Float::nan()` if the
  269. /// number is `Float::nan()`.
  270. ///
  271. /// ```
  272. /// use num_traits::Float;
  273. /// use std::f64;
  274. ///
  275. /// let x = 3.5;
  276. /// let y = -3.5;
  277. ///
  278. /// let abs_difference_x = (x.abs() - x).abs();
  279. /// let abs_difference_y = (y.abs() - (-y)).abs();
  280. ///
  281. /// assert!(abs_difference_x < 1e-10);
  282. /// assert!(abs_difference_y < 1e-10);
  283. ///
  284. /// assert!(f64::NAN.abs().is_nan());
  285. /// ```
  286. fn abs(self) -> Self;
  287. /// Returns a number that represents the sign of `self`.
  288. ///
  289. /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
  290. /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
  291. /// - `Float::nan()` if the number is `Float::nan()`
  292. ///
  293. /// ```
  294. /// use num_traits::Float;
  295. /// use std::f64;
  296. ///
  297. /// let f = 3.5;
  298. ///
  299. /// assert_eq!(f.signum(), 1.0);
  300. /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
  301. ///
  302. /// assert!(f64::NAN.signum().is_nan());
  303. /// ```
  304. fn signum(self) -> Self;
  305. /// Returns `true` if `self` is positive, including `+0.0` and
  306. /// `Float::infinity()`.
  307. ///
  308. /// ```
  309. /// use num_traits::Float;
  310. /// use std::f64;
  311. ///
  312. /// let nan: f64 = f64::NAN;
  313. ///
  314. /// let f = 7.0;
  315. /// let g = -7.0;
  316. ///
  317. /// assert!(f.is_sign_positive());
  318. /// assert!(!g.is_sign_positive());
  319. /// // Requires both tests to determine if is `NaN`
  320. /// assert!(!nan.is_sign_positive() && !nan.is_sign_negative());
  321. /// ```
  322. fn is_sign_positive(self) -> bool;
  323. /// Returns `true` if `self` is negative, including `-0.0` and
  324. /// `Float::neg_infinity()`.
  325. ///
  326. /// ```
  327. /// use num_traits::Float;
  328. /// use std::f64;
  329. ///
  330. /// let nan = f64::NAN;
  331. ///
  332. /// let f = 7.0;
  333. /// let g = -7.0;
  334. ///
  335. /// assert!(!f.is_sign_negative());
  336. /// assert!(g.is_sign_negative());
  337. /// // Requires both tests to determine if is `NaN`.
  338. /// assert!(!nan.is_sign_positive() && !nan.is_sign_negative());
  339. /// ```
  340. fn is_sign_negative(self) -> bool;
  341. /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
  342. /// error. This produces a more accurate result with better performance than
  343. /// a separate multiplication operation followed by an add.
  344. ///
  345. /// ```
  346. /// use num_traits::Float;
  347. ///
  348. /// let m = 10.0;
  349. /// let x = 4.0;
  350. /// let b = 60.0;
  351. ///
  352. /// // 100.0
  353. /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs();
  354. ///
  355. /// assert!(abs_difference < 1e-10);
  356. /// ```
  357. fn mul_add(self, a: Self, b: Self) -> Self;
  358. /// Take the reciprocal (inverse) of a number, `1/x`.
  359. ///
  360. /// ```
  361. /// use num_traits::Float;
  362. ///
  363. /// let x = 2.0;
  364. /// let abs_difference = (x.recip() - (1.0/x)).abs();
  365. ///
  366. /// assert!(abs_difference < 1e-10);
  367. /// ```
  368. fn recip(self) -> Self;
  369. /// Raise a number to an integer power.
  370. ///
  371. /// Using this function is generally faster than using `powf`
  372. ///
  373. /// ```
  374. /// use num_traits::Float;
  375. ///
  376. /// let x = 2.0;
  377. /// let abs_difference = (x.powi(2) - x*x).abs();
  378. ///
  379. /// assert!(abs_difference < 1e-10);
  380. /// ```
  381. fn powi(self, n: i32) -> Self;
  382. /// Raise a number to a floating point power.
  383. ///
  384. /// ```
  385. /// use num_traits::Float;
  386. ///
  387. /// let x = 2.0;
  388. /// let abs_difference = (x.powf(2.0) - x*x).abs();
  389. ///
  390. /// assert!(abs_difference < 1e-10);
  391. /// ```
  392. fn powf(self, n: Self) -> Self;
  393. /// Take the square root of a number.
  394. ///
  395. /// Returns NaN if `self` is a negative number.
  396. ///
  397. /// ```
  398. /// use num_traits::Float;
  399. ///
  400. /// let positive = 4.0;
  401. /// let negative = -4.0;
  402. ///
  403. /// let abs_difference = (positive.sqrt() - 2.0).abs();
  404. ///
  405. /// assert!(abs_difference < 1e-10);
  406. /// assert!(negative.sqrt().is_nan());
  407. /// ```
  408. fn sqrt(self) -> Self;
  409. /// Returns `e^(self)`, (the exponential function).
  410. ///
  411. /// ```
  412. /// use num_traits::Float;
  413. ///
  414. /// let one = 1.0;
  415. /// // e^1
  416. /// let e = one.exp();
  417. ///
  418. /// // ln(e) - 1 == 0
  419. /// let abs_difference = (e.ln() - 1.0).abs();
  420. ///
  421. /// assert!(abs_difference < 1e-10);
  422. /// ```
  423. fn exp(self) -> Self;
  424. /// Returns `2^(self)`.
  425. ///
  426. /// ```
  427. /// use num_traits::Float;
  428. ///
  429. /// let f = 2.0;
  430. ///
  431. /// // 2^2 - 4 == 0
  432. /// let abs_difference = (f.exp2() - 4.0).abs();
  433. ///
  434. /// assert!(abs_difference < 1e-10);
  435. /// ```
  436. fn exp2(self) -> Self;
  437. /// Returns the natural logarithm of the number.
  438. ///
  439. /// ```
  440. /// use num_traits::Float;
  441. ///
  442. /// let one = 1.0;
  443. /// // e^1
  444. /// let e = one.exp();
  445. ///
  446. /// // ln(e) - 1 == 0
  447. /// let abs_difference = (e.ln() - 1.0).abs();
  448. ///
  449. /// assert!(abs_difference < 1e-10);
  450. /// ```
  451. fn ln(self) -> Self;
  452. /// Returns the logarithm of the number with respect to an arbitrary base.
  453. ///
  454. /// ```
  455. /// use num_traits::Float;
  456. ///
  457. /// let ten = 10.0;
  458. /// let two = 2.0;
  459. ///
  460. /// // log10(10) - 1 == 0
  461. /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs();
  462. ///
  463. /// // log2(2) - 1 == 0
  464. /// let abs_difference_2 = (two.log(2.0) - 1.0).abs();
  465. ///
  466. /// assert!(abs_difference_10 < 1e-10);
  467. /// assert!(abs_difference_2 < 1e-10);
  468. /// ```
  469. fn log(self, base: Self) -> Self;
  470. /// Returns the base 2 logarithm of the number.
  471. ///
  472. /// ```
  473. /// use num_traits::Float;
  474. ///
  475. /// let two = 2.0;
  476. ///
  477. /// // log2(2) - 1 == 0
  478. /// let abs_difference = (two.log2() - 1.0).abs();
  479. ///
  480. /// assert!(abs_difference < 1e-10);
  481. /// ```
  482. fn log2(self) -> Self;
  483. /// Returns the base 10 logarithm of the number.
  484. ///
  485. /// ```
  486. /// use num_traits::Float;
  487. ///
  488. /// let ten = 10.0;
  489. ///
  490. /// // log10(10) - 1 == 0
  491. /// let abs_difference = (ten.log10() - 1.0).abs();
  492. ///
  493. /// assert!(abs_difference < 1e-10);
  494. /// ```
  495. fn log10(self) -> Self;
  496. /// Converts radians to degrees.
  497. ///
  498. /// ```
  499. /// use std::f64::consts;
  500. ///
  501. /// let angle = consts::PI;
  502. ///
  503. /// let abs_difference = (angle.to_degrees() - 180.0).abs();
  504. ///
  505. /// assert!(abs_difference < 1e-10);
  506. /// ```
  507. #[inline]
  508. fn to_degrees(self) -> Self {
  509. let halfpi = Self::zero().acos();
  510. let ninety = Self::from(90u8).unwrap();
  511. self * ninety / halfpi
  512. }
  513. /// Converts degrees to radians.
  514. ///
  515. /// ```
  516. /// use std::f64::consts;
  517. ///
  518. /// let angle = 180.0_f64;
  519. ///
  520. /// let abs_difference = (angle.to_radians() - consts::PI).abs();
  521. ///
  522. /// assert!(abs_difference < 1e-10);
  523. /// ```
  524. #[inline]
  525. fn to_radians(self) -> Self {
  526. let halfpi = Self::zero().acos();
  527. let ninety = Self::from(90u8).unwrap();
  528. self * halfpi / ninety
  529. }
  530. /// Returns the maximum of the two numbers.
  531. ///
  532. /// ```
  533. /// use num_traits::Float;
  534. ///
  535. /// let x = 1.0;
  536. /// let y = 2.0;
  537. ///
  538. /// assert_eq!(x.max(y), y);
  539. /// ```
  540. fn max(self, other: Self) -> Self;
  541. /// Returns the minimum of the two numbers.
  542. ///
  543. /// ```
  544. /// use num_traits::Float;
  545. ///
  546. /// let x = 1.0;
  547. /// let y = 2.0;
  548. ///
  549. /// assert_eq!(x.min(y), x);
  550. /// ```
  551. fn min(self, other: Self) -> Self;
  552. /// The positive difference of two numbers.
  553. ///
  554. /// * If `self <= other`: `0:0`
  555. /// * Else: `self - other`
  556. ///
  557. /// ```
  558. /// use num_traits::Float;
  559. ///
  560. /// let x = 3.0;
  561. /// let y = -3.0;
  562. ///
  563. /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
  564. /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();
  565. ///
  566. /// assert!(abs_difference_x < 1e-10);
  567. /// assert!(abs_difference_y < 1e-10);
  568. /// ```
  569. fn abs_sub(self, other: Self) -> Self;
  570. /// Take the cubic root of a number.
  571. ///
  572. /// ```
  573. /// use num_traits::Float;
  574. ///
  575. /// let x = 8.0;
  576. ///
  577. /// // x^(1/3) - 2 == 0
  578. /// let abs_difference = (x.cbrt() - 2.0).abs();
  579. ///
  580. /// assert!(abs_difference < 1e-10);
  581. /// ```
  582. fn cbrt(self) -> Self;
  583. /// Calculate the length of the hypotenuse of a right-angle triangle given
  584. /// legs of length `x` and `y`.
  585. ///
  586. /// ```
  587. /// use num_traits::Float;
  588. ///
  589. /// let x = 2.0;
  590. /// let y = 3.0;
  591. ///
  592. /// // sqrt(x^2 + y^2)
  593. /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
  594. ///
  595. /// assert!(abs_difference < 1e-10);
  596. /// ```
  597. fn hypot(self, other: Self) -> Self;
  598. /// Computes the sine of a number (in radians).
  599. ///
  600. /// ```
  601. /// use num_traits::Float;
  602. /// use std::f64;
  603. ///
  604. /// let x = f64::consts::PI/2.0;
  605. ///
  606. /// let abs_difference = (x.sin() - 1.0).abs();
  607. ///
  608. /// assert!(abs_difference < 1e-10);
  609. /// ```
  610. fn sin(self) -> Self;
  611. /// Computes the cosine of a number (in radians).
  612. ///
  613. /// ```
  614. /// use num_traits::Float;
  615. /// use std::f64;
  616. ///
  617. /// let x = 2.0*f64::consts::PI;
  618. ///
  619. /// let abs_difference = (x.cos() - 1.0).abs();
  620. ///
  621. /// assert!(abs_difference < 1e-10);
  622. /// ```
  623. fn cos(self) -> Self;
  624. /// Computes the tangent of a number (in radians).
  625. ///
  626. /// ```
  627. /// use num_traits::Float;
  628. /// use std::f64;
  629. ///
  630. /// let x = f64::consts::PI/4.0;
  631. /// let abs_difference = (x.tan() - 1.0).abs();
  632. ///
  633. /// assert!(abs_difference < 1e-14);
  634. /// ```
  635. fn tan(self) -> Self;
  636. /// Computes the arcsine of a number. Return value is in radians in
  637. /// the range [-pi/2, pi/2] or NaN if the number is outside the range
  638. /// [-1, 1].
  639. ///
  640. /// ```
  641. /// use num_traits::Float;
  642. /// use std::f64;
  643. ///
  644. /// let f = f64::consts::PI / 2.0;
  645. ///
  646. /// // asin(sin(pi/2))
  647. /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs();
  648. ///
  649. /// assert!(abs_difference < 1e-10);
  650. /// ```
  651. fn asin(self) -> Self;
  652. /// Computes the arccosine of a number. Return value is in radians in
  653. /// the range [0, pi] or NaN if the number is outside the range
  654. /// [-1, 1].
  655. ///
  656. /// ```
  657. /// use num_traits::Float;
  658. /// use std::f64;
  659. ///
  660. /// let f = f64::consts::PI / 4.0;
  661. ///
  662. /// // acos(cos(pi/4))
  663. /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs();
  664. ///
  665. /// assert!(abs_difference < 1e-10);
  666. /// ```
  667. fn acos(self) -> Self;
  668. /// Computes the arctangent of a number. Return value is in radians in the
  669. /// range [-pi/2, pi/2];
  670. ///
  671. /// ```
  672. /// use num_traits::Float;
  673. ///
  674. /// let f = 1.0;
  675. ///
  676. /// // atan(tan(1))
  677. /// let abs_difference = (f.tan().atan() - 1.0).abs();
  678. ///
  679. /// assert!(abs_difference < 1e-10);
  680. /// ```
  681. fn atan(self) -> Self;
  682. /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`).
  683. ///
  684. /// * `x = 0`, `y = 0`: `0`
  685. /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
  686. /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
  687. /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
  688. ///
  689. /// ```
  690. /// use num_traits::Float;
  691. /// use std::f64;
  692. ///
  693. /// let pi = f64::consts::PI;
  694. /// // All angles from horizontal right (+x)
  695. /// // 45 deg counter-clockwise
  696. /// let x1 = 3.0;
  697. /// let y1 = -3.0;
  698. ///
  699. /// // 135 deg clockwise
  700. /// let x2 = -3.0;
  701. /// let y2 = 3.0;
  702. ///
  703. /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs();
  704. /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs();
  705. ///
  706. /// assert!(abs_difference_1 < 1e-10);
  707. /// assert!(abs_difference_2 < 1e-10);
  708. /// ```
  709. fn atan2(self, other: Self) -> Self;
  710. /// Simultaneously computes the sine and cosine of the number, `x`. Returns
  711. /// `(sin(x), cos(x))`.
  712. ///
  713. /// ```
  714. /// use num_traits::Float;
  715. /// use std::f64;
  716. ///
  717. /// let x = f64::consts::PI/4.0;
  718. /// let f = x.sin_cos();
  719. ///
  720. /// let abs_difference_0 = (f.0 - x.sin()).abs();
  721. /// let abs_difference_1 = (f.1 - x.cos()).abs();
  722. ///
  723. /// assert!(abs_difference_0 < 1e-10);
  724. /// assert!(abs_difference_0 < 1e-10);
  725. /// ```
  726. fn sin_cos(self) -> (Self, Self);
  727. /// Returns `e^(self) - 1` in a way that is accurate even if the
  728. /// number is close to zero.
  729. ///
  730. /// ```
  731. /// use num_traits::Float;
  732. ///
  733. /// let x = 7.0;
  734. ///
  735. /// // e^(ln(7)) - 1
  736. /// let abs_difference = (x.ln().exp_m1() - 6.0).abs();
  737. ///
  738. /// assert!(abs_difference < 1e-10);
  739. /// ```
  740. fn exp_m1(self) -> Self;
  741. /// Returns `ln(1+n)` (natural logarithm) more accurately than if
  742. /// the operations were performed separately.
  743. ///
  744. /// ```
  745. /// use num_traits::Float;
  746. /// use std::f64;
  747. ///
  748. /// let x = f64::consts::E - 1.0;
  749. ///
  750. /// // ln(1 + (e - 1)) == ln(e) == 1
  751. /// let abs_difference = (x.ln_1p() - 1.0).abs();
  752. ///
  753. /// assert!(abs_difference < 1e-10);
  754. /// ```
  755. fn ln_1p(self) -> Self;
  756. /// Hyperbolic sine function.
  757. ///
  758. /// ```
  759. /// use num_traits::Float;
  760. /// use std::f64;
  761. ///
  762. /// let e = f64::consts::E;
  763. /// let x = 1.0;
  764. ///
  765. /// let f = x.sinh();
  766. /// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
  767. /// let g = (e*e - 1.0)/(2.0*e);
  768. /// let abs_difference = (f - g).abs();
  769. ///
  770. /// assert!(abs_difference < 1e-10);
  771. /// ```
  772. fn sinh(self) -> Self;
  773. /// Hyperbolic cosine function.
  774. ///
  775. /// ```
  776. /// use num_traits::Float;
  777. /// use std::f64;
  778. ///
  779. /// let e = f64::consts::E;
  780. /// let x = 1.0;
  781. /// let f = x.cosh();
  782. /// // Solving cosh() at 1 gives this result
  783. /// let g = (e*e + 1.0)/(2.0*e);
  784. /// let abs_difference = (f - g).abs();
  785. ///
  786. /// // Same result
  787. /// assert!(abs_difference < 1.0e-10);
  788. /// ```
  789. fn cosh(self) -> Self;
  790. /// Hyperbolic tangent function.
  791. ///
  792. /// ```
  793. /// use num_traits::Float;
  794. /// use std::f64;
  795. ///
  796. /// let e = f64::consts::E;
  797. /// let x = 1.0;
  798. ///
  799. /// let f = x.tanh();
  800. /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
  801. /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2));
  802. /// let abs_difference = (f - g).abs();
  803. ///
  804. /// assert!(abs_difference < 1.0e-10);
  805. /// ```
  806. fn tanh(self) -> Self;
  807. /// Inverse hyperbolic sine function.
  808. ///
  809. /// ```
  810. /// use num_traits::Float;
  811. ///
  812. /// let x = 1.0;
  813. /// let f = x.sinh().asinh();
  814. ///
  815. /// let abs_difference = (f - x).abs();
  816. ///
  817. /// assert!(abs_difference < 1.0e-10);
  818. /// ```
  819. fn asinh(self) -> Self;
  820. /// Inverse hyperbolic cosine function.
  821. ///
  822. /// ```
  823. /// use num_traits::Float;
  824. ///
  825. /// let x = 1.0;
  826. /// let f = x.cosh().acosh();
  827. ///
  828. /// let abs_difference = (f - x).abs();
  829. ///
  830. /// assert!(abs_difference < 1.0e-10);
  831. /// ```
  832. fn acosh(self) -> Self;
  833. /// Inverse hyperbolic tangent function.
  834. ///
  835. /// ```
  836. /// use num_traits::Float;
  837. /// use std::f64;
  838. ///
  839. /// let e = f64::consts::E;
  840. /// let f = e.tanh().atanh();
  841. ///
  842. /// let abs_difference = (f - e).abs();
  843. ///
  844. /// assert!(abs_difference < 1.0e-10);
  845. /// ```
  846. fn atanh(self) -> Self;
  847. /// Returns the mantissa, base 2 exponent, and sign as integers, respectively.
  848. /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`.
  849. /// The floating point encoding is documented in the [Reference][floating-point].
  850. ///
  851. /// ```
  852. /// use num_traits::Float;
  853. ///
  854. /// let num = 2.0f32;
  855. ///
  856. /// // (8388608, -22, 1)
  857. /// let (mantissa, exponent, sign) = Float::integer_decode(num);
  858. /// let sign_f = sign as f32;
  859. /// let mantissa_f = mantissa as f32;
  860. /// let exponent_f = num.powf(exponent as f32);
  861. ///
  862. /// // 1 * 8388608 * 2^(-22) == 2
  863. /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs();
  864. ///
  865. /// assert!(abs_difference < 1e-10);
  866. /// ```
  867. /// [floating-point]: ../../../../../reference.html#machine-types
  868. fn integer_decode(self) -> (u64, i16, i8);
  869. }
  870. macro_rules! float_impl {
  871. ($T:ident $decode:ident) => (
  872. impl Float for $T {
  873. #[inline]
  874. fn nan() -> Self {
  875. ::std::$T::NAN
  876. }
  877. #[inline]
  878. fn infinity() -> Self {
  879. ::std::$T::INFINITY
  880. }
  881. #[inline]
  882. fn neg_infinity() -> Self {
  883. ::std::$T::NEG_INFINITY
  884. }
  885. #[inline]
  886. fn neg_zero() -> Self {
  887. -0.0
  888. }
  889. #[inline]
  890. fn min_value() -> Self {
  891. ::std::$T::MIN
  892. }
  893. #[inline]
  894. fn min_positive_value() -> Self {
  895. ::std::$T::MIN_POSITIVE
  896. }
  897. #[inline]
  898. fn epsilon() -> Self {
  899. ::std::$T::EPSILON
  900. }
  901. #[inline]
  902. fn max_value() -> Self {
  903. ::std::$T::MAX
  904. }
  905. #[inline]
  906. fn is_nan(self) -> bool {
  907. <$T>::is_nan(self)
  908. }
  909. #[inline]
  910. fn is_infinite(self) -> bool {
  911. <$T>::is_infinite(self)
  912. }
  913. #[inline]
  914. fn is_finite(self) -> bool {
  915. <$T>::is_finite(self)
  916. }
  917. #[inline]
  918. fn is_normal(self) -> bool {
  919. <$T>::is_normal(self)
  920. }
  921. #[inline]
  922. fn classify(self) -> FpCategory {
  923. <$T>::classify(self)
  924. }
  925. #[inline]
  926. fn floor(self) -> Self {
  927. <$T>::floor(self)
  928. }
  929. #[inline]
  930. fn ceil(self) -> Self {
  931. <$T>::ceil(self)
  932. }
  933. #[inline]
  934. fn round(self) -> Self {
  935. <$T>::round(self)
  936. }
  937. #[inline]
  938. fn trunc(self) -> Self {
  939. <$T>::trunc(self)
  940. }
  941. #[inline]
  942. fn fract(self) -> Self {
  943. <$T>::fract(self)
  944. }
  945. #[inline]
  946. fn abs(self) -> Self {
  947. <$T>::abs(self)
  948. }
  949. #[inline]
  950. fn signum(self) -> Self {
  951. <$T>::signum(self)
  952. }
  953. #[inline]
  954. fn is_sign_positive(self) -> bool {
  955. <$T>::is_sign_positive(self)
  956. }
  957. #[inline]
  958. fn is_sign_negative(self) -> bool {
  959. <$T>::is_sign_negative(self)
  960. }
  961. #[inline]
  962. fn mul_add(self, a: Self, b: Self) -> Self {
  963. <$T>::mul_add(self, a, b)
  964. }
  965. #[inline]
  966. fn recip(self) -> Self {
  967. <$T>::recip(self)
  968. }
  969. #[inline]
  970. fn powi(self, n: i32) -> Self {
  971. <$T>::powi(self, n)
  972. }
  973. #[inline]
  974. fn powf(self, n: Self) -> Self {
  975. <$T>::powf(self, n)
  976. }
  977. #[inline]
  978. fn sqrt(self) -> Self {
  979. <$T>::sqrt(self)
  980. }
  981. #[inline]
  982. fn exp(self) -> Self {
  983. <$T>::exp(self)
  984. }
  985. #[inline]
  986. fn exp2(self) -> Self {
  987. <$T>::exp2(self)
  988. }
  989. #[inline]
  990. fn ln(self) -> Self {
  991. <$T>::ln(self)
  992. }
  993. #[inline]
  994. fn log(self, base: Self) -> Self {
  995. <$T>::log(self, base)
  996. }
  997. #[inline]
  998. fn log2(self) -> Self {
  999. <$T>::log2(self)
  1000. }
  1001. #[inline]
  1002. fn log10(self) -> Self {
  1003. <$T>::log10(self)
  1004. }
  1005. #[inline]
  1006. fn to_degrees(self) -> Self {
  1007. // NB: `f32` didn't stabilize this until 1.7
  1008. // <$T>::to_degrees(self)
  1009. self * (180. / ::std::$T::consts::PI)
  1010. }
  1011. #[inline]
  1012. fn to_radians(self) -> Self {
  1013. // NB: `f32` didn't stabilize this until 1.7
  1014. // <$T>::to_radians(self)
  1015. self * (::std::$T::consts::PI / 180.)
  1016. }
  1017. #[inline]
  1018. fn max(self, other: Self) -> Self {
  1019. <$T>::max(self, other)
  1020. }
  1021. #[inline]
  1022. fn min(self, other: Self) -> Self {
  1023. <$T>::min(self, other)
  1024. }
  1025. #[inline]
  1026. #[allow(deprecated)]
  1027. fn abs_sub(self, other: Self) -> Self {
  1028. <$T>::abs_sub(self, other)
  1029. }
  1030. #[inline]
  1031. fn cbrt(self) -> Self {
  1032. <$T>::cbrt(self)
  1033. }
  1034. #[inline]
  1035. fn hypot(self, other: Self) -> Self {
  1036. <$T>::hypot(self, other)
  1037. }
  1038. #[inline]
  1039. fn sin(self) -> Self {
  1040. <$T>::sin(self)
  1041. }
  1042. #[inline]
  1043. fn cos(self) -> Self {
  1044. <$T>::cos(self)
  1045. }
  1046. #[inline]
  1047. fn tan(self) -> Self {
  1048. <$T>::tan(self)
  1049. }
  1050. #[inline]
  1051. fn asin(self) -> Self {
  1052. <$T>::asin(self)
  1053. }
  1054. #[inline]
  1055. fn acos(self) -> Self {
  1056. <$T>::acos(self)
  1057. }
  1058. #[inline]
  1059. fn atan(self) -> Self {
  1060. <$T>::atan(self)
  1061. }
  1062. #[inline]
  1063. fn atan2(self, other: Self) -> Self {
  1064. <$T>::atan2(self, other)
  1065. }
  1066. #[inline]
  1067. fn sin_cos(self) -> (Self, Self) {
  1068. <$T>::sin_cos(self)
  1069. }
  1070. #[inline]
  1071. fn exp_m1(self) -> Self {
  1072. <$T>::exp_m1(self)
  1073. }
  1074. #[inline]
  1075. fn ln_1p(self) -> Self {
  1076. <$T>::ln_1p(self)
  1077. }
  1078. #[inline]
  1079. fn sinh(self) -> Self {
  1080. <$T>::sinh(self)
  1081. }
  1082. #[inline]
  1083. fn cosh(self) -> Self {
  1084. <$T>::cosh(self)
  1085. }
  1086. #[inline]
  1087. fn tanh(self) -> Self {
  1088. <$T>::tanh(self)
  1089. }
  1090. #[inline]
  1091. fn asinh(self) -> Self {
  1092. <$T>::asinh(self)
  1093. }
  1094. #[inline]
  1095. fn acosh(self) -> Self {
  1096. <$T>::acosh(self)
  1097. }
  1098. #[inline]
  1099. fn atanh(self) -> Self {
  1100. <$T>::atanh(self)
  1101. }
  1102. #[inline]
  1103. fn integer_decode(self) -> (u64, i16, i8) {
  1104. $decode(self)
  1105. }
  1106. }
  1107. )
  1108. }
  1109. fn integer_decode_f32(f: f32) -> (u64, i16, i8) {
  1110. let bits: u32 = unsafe { mem::transmute(f) };
  1111. let sign: i8 = if bits >> 31 == 0 {
  1112. 1
  1113. } else {
  1114. -1
  1115. };
  1116. let mut exponent: i16 = ((bits >> 23) & 0xff) as i16;
  1117. let mantissa = if exponent == 0 {
  1118. (bits & 0x7fffff) << 1
  1119. } else {
  1120. (bits & 0x7fffff) | 0x800000
  1121. };
  1122. // Exponent bias + mantissa shift
  1123. exponent -= 127 + 23;
  1124. (mantissa as u64, exponent, sign)
  1125. }
  1126. fn integer_decode_f64(f: f64) -> (u64, i16, i8) {
  1127. let bits: u64 = unsafe { mem::transmute(f) };
  1128. let sign: i8 = if bits >> 63 == 0 {
  1129. 1
  1130. } else {
  1131. -1
  1132. };
  1133. let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
  1134. let mantissa = if exponent == 0 {
  1135. (bits & 0xfffffffffffff) << 1
  1136. } else {
  1137. (bits & 0xfffffffffffff) | 0x10000000000000
  1138. };
  1139. // Exponent bias + mantissa shift
  1140. exponent -= 1023 + 52;
  1141. (mantissa, exponent, sign)
  1142. }
  1143. float_impl!(f32 integer_decode_f32);
  1144. float_impl!(f64 integer_decode_f64);
  1145. macro_rules! float_const_impl {
  1146. ($(#[$doc:meta] $constant:ident,)+) => (
  1147. #[allow(non_snake_case)]
  1148. pub trait FloatConst {
  1149. $(#[$doc] fn $constant() -> Self;)+
  1150. }
  1151. float_const_impl! { @float f32, $($constant,)+ }
  1152. float_const_impl! { @float f64, $($constant,)+ }
  1153. );
  1154. (@float $T:ident, $($constant:ident,)+) => (
  1155. impl FloatConst for $T {
  1156. $(
  1157. #[inline]
  1158. fn $constant() -> Self {
  1159. ::std::$T::consts::$constant
  1160. }
  1161. )+
  1162. }
  1163. );
  1164. }
  1165. float_const_impl! {
  1166. #[doc = "Return Euler’s number."]
  1167. E,
  1168. #[doc = "Return `1.0 / π`."]
  1169. FRAC_1_PI,
  1170. #[doc = "Return `1.0 / sqrt(2.0)`."]
  1171. FRAC_1_SQRT_2,
  1172. #[doc = "Return `2.0 / π`."]
  1173. FRAC_2_PI,
  1174. #[doc = "Return `2.0 / sqrt(π)`."]
  1175. FRAC_2_SQRT_PI,
  1176. #[doc = "Return `π / 2.0`."]
  1177. FRAC_PI_2,
  1178. #[doc = "Return `π / 3.0`."]
  1179. FRAC_PI_3,
  1180. #[doc = "Return `π / 4.0`."]
  1181. FRAC_PI_4,
  1182. #[doc = "Return `π / 6.0`."]
  1183. FRAC_PI_6,
  1184. #[doc = "Return `π / 8.0`."]
  1185. FRAC_PI_8,
  1186. #[doc = "Return `ln(10.0)`."]
  1187. LN_10,
  1188. #[doc = "Return `ln(2.0)`."]
  1189. LN_2,
  1190. #[doc = "Return `log10(e)`."]
  1191. LOG10_E,
  1192. #[doc = "Return `log2(e)`."]
  1193. LOG2_E,
  1194. #[doc = "Return Archimedes’ constant."]
  1195. PI,
  1196. #[doc = "Return `sqrt(2.0)`."]
  1197. SQRT_2,
  1198. }
  1199. #[cfg(test)]
  1200. mod tests {
  1201. use Float;
  1202. #[test]
  1203. fn convert_deg_rad() {
  1204. use std::f64::consts;
  1205. const DEG_RAD_PAIRS: [(f64, f64); 7] = [
  1206. (0.0, 0.),
  1207. (22.5, consts::FRAC_PI_8),
  1208. (30.0, consts::FRAC_PI_6),
  1209. (45.0, consts::FRAC_PI_4),
  1210. (60.0, consts::FRAC_PI_3),
  1211. (90.0, consts::FRAC_PI_2),
  1212. (180.0, consts::PI),
  1213. ];
  1214. for &(deg, rad) in &DEG_RAD_PAIRS {
  1215. assert!((Float::to_degrees(rad) - deg).abs() < 1e-6);
  1216. assert!((Float::to_radians(deg) - rad).abs() < 1e-6);
  1217. let (deg, rad) = (deg as f32, rad as f32);
  1218. assert!((Float::to_degrees(rad) - deg).abs() < 1e-6);
  1219. assert!((Float::to_radians(deg) - rad).abs() < 1e-6);
  1220. }
  1221. }
  1222. }