float.rs 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351
  1. use core::mem;
  2. use core::num::FpCategory;
  3. use core::ops::{Add, Div, Neg};
  4. use core::f32;
  5. use core::f64;
  6. use {Num, NumCast, ToPrimitive};
  7. #[cfg(all(not(feature = "std"), feature = "libm"))]
  8. use libm;
  9. /// Generic trait for floating point numbers that works with `no_std`.
  10. ///
  11. /// This trait implements a subset of the `Float` trait.
  12. pub trait FloatCore: Num + NumCast + Neg<Output = Self> + PartialOrd + Copy {
  13. /// Returns positive infinity.
  14. ///
  15. /// # Examples
  16. ///
  17. /// ```
  18. /// use num_traits::float::FloatCore;
  19. /// use std::{f32, f64};
  20. ///
  21. /// fn check<T: FloatCore>(x: T) {
  22. /// assert!(T::infinity() == x);
  23. /// }
  24. ///
  25. /// check(f32::INFINITY);
  26. /// check(f64::INFINITY);
  27. /// ```
  28. fn infinity() -> Self;
  29. /// Returns negative infinity.
  30. ///
  31. /// # Examples
  32. ///
  33. /// ```
  34. /// use num_traits::float::FloatCore;
  35. /// use std::{f32, f64};
  36. ///
  37. /// fn check<T: FloatCore>(x: T) {
  38. /// assert!(T::neg_infinity() == x);
  39. /// }
  40. ///
  41. /// check(f32::NEG_INFINITY);
  42. /// check(f64::NEG_INFINITY);
  43. /// ```
  44. fn neg_infinity() -> Self;
  45. /// Returns NaN.
  46. ///
  47. /// # Examples
  48. ///
  49. /// ```
  50. /// use num_traits::float::FloatCore;
  51. ///
  52. /// fn check<T: FloatCore>() {
  53. /// let n = T::nan();
  54. /// assert!(n != n);
  55. /// }
  56. ///
  57. /// check::<f32>();
  58. /// check::<f64>();
  59. /// ```
  60. fn nan() -> Self;
  61. /// Returns `-0.0`.
  62. ///
  63. /// # Examples
  64. ///
  65. /// ```
  66. /// use num_traits::float::FloatCore;
  67. /// use std::{f32, f64};
  68. ///
  69. /// fn check<T: FloatCore>(n: T) {
  70. /// let z = T::neg_zero();
  71. /// assert!(z.is_zero());
  72. /// assert!(T::one() / z == n);
  73. /// }
  74. ///
  75. /// check(f32::NEG_INFINITY);
  76. /// check(f64::NEG_INFINITY);
  77. /// ```
  78. fn neg_zero() -> Self;
  79. /// Returns the smallest finite value that this type can represent.
  80. ///
  81. /// # Examples
  82. ///
  83. /// ```
  84. /// use num_traits::float::FloatCore;
  85. /// use std::{f32, f64};
  86. ///
  87. /// fn check<T: FloatCore>(x: T) {
  88. /// assert!(T::min_value() == x);
  89. /// }
  90. ///
  91. /// check(f32::MIN);
  92. /// check(f64::MIN);
  93. /// ```
  94. fn min_value() -> Self;
  95. /// Returns the smallest positive, normalized value that this type can represent.
  96. ///
  97. /// # Examples
  98. ///
  99. /// ```
  100. /// use num_traits::float::FloatCore;
  101. /// use std::{f32, f64};
  102. ///
  103. /// fn check<T: FloatCore>(x: T) {
  104. /// assert!(T::min_positive_value() == x);
  105. /// }
  106. ///
  107. /// check(f32::MIN_POSITIVE);
  108. /// check(f64::MIN_POSITIVE);
  109. /// ```
  110. fn min_positive_value() -> Self;
  111. /// Returns epsilon, a small positive value.
  112. ///
  113. /// # Examples
  114. ///
  115. /// ```
  116. /// use num_traits::float::FloatCore;
  117. /// use std::{f32, f64};
  118. ///
  119. /// fn check<T: FloatCore>(x: T) {
  120. /// assert!(T::epsilon() == x);
  121. /// }
  122. ///
  123. /// check(f32::EPSILON);
  124. /// check(f64::EPSILON);
  125. /// ```
  126. fn epsilon() -> Self;
  127. /// Returns the largest finite value that this type can represent.
  128. ///
  129. /// # Examples
  130. ///
  131. /// ```
  132. /// use num_traits::float::FloatCore;
  133. /// use std::{f32, f64};
  134. ///
  135. /// fn check<T: FloatCore>(x: T) {
  136. /// assert!(T::max_value() == x);
  137. /// }
  138. ///
  139. /// check(f32::MAX);
  140. /// check(f64::MAX);
  141. /// ```
  142. fn max_value() -> Self;
  143. /// Returns `true` if the number is NaN.
  144. ///
  145. /// # Examples
  146. ///
  147. /// ```
  148. /// use num_traits::float::FloatCore;
  149. /// use std::{f32, f64};
  150. ///
  151. /// fn check<T: FloatCore>(x: T, p: bool) {
  152. /// assert!(x.is_nan() == p);
  153. /// }
  154. ///
  155. /// check(f32::NAN, true);
  156. /// check(f32::INFINITY, false);
  157. /// check(f64::NAN, true);
  158. /// check(0.0f64, false);
  159. /// ```
  160. #[inline]
  161. fn is_nan(self) -> bool {
  162. self != self
  163. }
  164. /// Returns `true` if the number is infinite.
  165. ///
  166. /// # Examples
  167. ///
  168. /// ```
  169. /// use num_traits::float::FloatCore;
  170. /// use std::{f32, f64};
  171. ///
  172. /// fn check<T: FloatCore>(x: T, p: bool) {
  173. /// assert!(x.is_infinite() == p);
  174. /// }
  175. ///
  176. /// check(f32::INFINITY, true);
  177. /// check(f32::NEG_INFINITY, true);
  178. /// check(f32::NAN, false);
  179. /// check(f64::INFINITY, true);
  180. /// check(f64::NEG_INFINITY, true);
  181. /// check(0.0f64, false);
  182. /// ```
  183. #[inline]
  184. fn is_infinite(self) -> bool {
  185. self == Self::infinity() || self == Self::neg_infinity()
  186. }
  187. /// Returns `true` if the number is neither infinite or NaN.
  188. ///
  189. /// # Examples
  190. ///
  191. /// ```
  192. /// use num_traits::float::FloatCore;
  193. /// use std::{f32, f64};
  194. ///
  195. /// fn check<T: FloatCore>(x: T, p: bool) {
  196. /// assert!(x.is_finite() == p);
  197. /// }
  198. ///
  199. /// check(f32::INFINITY, false);
  200. /// check(f32::MAX, true);
  201. /// check(f64::NEG_INFINITY, false);
  202. /// check(f64::MIN_POSITIVE, true);
  203. /// check(f64::NAN, false);
  204. /// ```
  205. #[inline]
  206. fn is_finite(self) -> bool {
  207. !(self.is_nan() || self.is_infinite())
  208. }
  209. /// Returns `true` if the number is neither zero, infinite, subnormal or NaN.
  210. ///
  211. /// # Examples
  212. ///
  213. /// ```
  214. /// use num_traits::float::FloatCore;
  215. /// use std::{f32, f64};
  216. ///
  217. /// fn check<T: FloatCore>(x: T, p: bool) {
  218. /// assert!(x.is_normal() == p);
  219. /// }
  220. ///
  221. /// check(f32::INFINITY, false);
  222. /// check(f32::MAX, true);
  223. /// check(f64::NEG_INFINITY, false);
  224. /// check(f64::MIN_POSITIVE, true);
  225. /// check(0.0f64, false);
  226. /// ```
  227. #[inline]
  228. fn is_normal(self) -> bool {
  229. self.classify() == FpCategory::Normal
  230. }
  231. /// Returns the floating point category of the number. If only one property
  232. /// is going to be tested, it is generally faster to use the specific
  233. /// predicate instead.
  234. ///
  235. /// # Examples
  236. ///
  237. /// ```
  238. /// use num_traits::float::FloatCore;
  239. /// use std::{f32, f64};
  240. /// use std::num::FpCategory;
  241. ///
  242. /// fn check<T: FloatCore>(x: T, c: FpCategory) {
  243. /// assert!(x.classify() == c);
  244. /// }
  245. ///
  246. /// check(f32::INFINITY, FpCategory::Infinite);
  247. /// check(f32::MAX, FpCategory::Normal);
  248. /// check(f64::NAN, FpCategory::Nan);
  249. /// check(f64::MIN_POSITIVE, FpCategory::Normal);
  250. /// check(f64::MIN_POSITIVE / 2.0, FpCategory::Subnormal);
  251. /// check(0.0f64, FpCategory::Zero);
  252. /// ```
  253. fn classify(self) -> FpCategory;
  254. /// Returns the largest integer less than or equal to a number.
  255. ///
  256. /// # Examples
  257. ///
  258. /// ```
  259. /// use num_traits::float::FloatCore;
  260. /// use std::{f32, f64};
  261. ///
  262. /// fn check<T: FloatCore>(x: T, y: T) {
  263. /// assert!(x.floor() == y);
  264. /// }
  265. ///
  266. /// check(f32::INFINITY, f32::INFINITY);
  267. /// check(0.9f32, 0.0);
  268. /// check(1.0f32, 1.0);
  269. /// check(1.1f32, 1.0);
  270. /// check(-0.0f64, 0.0);
  271. /// check(-0.9f64, -1.0);
  272. /// check(-1.0f64, -1.0);
  273. /// check(-1.1f64, -2.0);
  274. /// check(f64::MIN, f64::MIN);
  275. /// ```
  276. #[inline]
  277. fn floor(self) -> Self {
  278. let f = self.fract();
  279. if f.is_nan() || f.is_zero() {
  280. self
  281. } else if self < Self::zero() {
  282. self - f - Self::one()
  283. } else {
  284. self - f
  285. }
  286. }
  287. /// Returns the smallest integer greater than or equal to a number.
  288. ///
  289. /// # Examples
  290. ///
  291. /// ```
  292. /// use num_traits::float::FloatCore;
  293. /// use std::{f32, f64};
  294. ///
  295. /// fn check<T: FloatCore>(x: T, y: T) {
  296. /// assert!(x.ceil() == y);
  297. /// }
  298. ///
  299. /// check(f32::INFINITY, f32::INFINITY);
  300. /// check(0.9f32, 1.0);
  301. /// check(1.0f32, 1.0);
  302. /// check(1.1f32, 2.0);
  303. /// check(-0.0f64, 0.0);
  304. /// check(-0.9f64, -0.0);
  305. /// check(-1.0f64, -1.0);
  306. /// check(-1.1f64, -1.0);
  307. /// check(f64::MIN, f64::MIN);
  308. /// ```
  309. #[inline]
  310. fn ceil(self) -> Self {
  311. let f = self.fract();
  312. if f.is_nan() || f.is_zero() {
  313. self
  314. } else if self > Self::zero() {
  315. self - f + Self::one()
  316. } else {
  317. self - f
  318. }
  319. }
  320. /// Returns the nearest integer to a number. Round half-way cases away from `0.0`.
  321. ///
  322. /// # Examples
  323. ///
  324. /// ```
  325. /// use num_traits::float::FloatCore;
  326. /// use std::{f32, f64};
  327. ///
  328. /// fn check<T: FloatCore>(x: T, y: T) {
  329. /// assert!(x.round() == y);
  330. /// }
  331. ///
  332. /// check(f32::INFINITY, f32::INFINITY);
  333. /// check(0.4f32, 0.0);
  334. /// check(0.5f32, 1.0);
  335. /// check(0.6f32, 1.0);
  336. /// check(-0.4f64, 0.0);
  337. /// check(-0.5f64, -1.0);
  338. /// check(-0.6f64, -1.0);
  339. /// check(f64::MIN, f64::MIN);
  340. /// ```
  341. #[inline]
  342. fn round(self) -> Self {
  343. let one = Self::one();
  344. let h = Self::from(0.5).expect("Unable to cast from 0.5");
  345. let f = self.fract();
  346. if f.is_nan() || f.is_zero() {
  347. self
  348. } else if self > Self::zero() {
  349. if f < h {
  350. self - f
  351. } else {
  352. self - f + one
  353. }
  354. } else {
  355. if -f < h {
  356. self - f
  357. } else {
  358. self - f - one
  359. }
  360. }
  361. }
  362. /// Return the integer part of a number.
  363. ///
  364. /// # Examples
  365. ///
  366. /// ```
  367. /// use num_traits::float::FloatCore;
  368. /// use std::{f32, f64};
  369. ///
  370. /// fn check<T: FloatCore>(x: T, y: T) {
  371. /// assert!(x.trunc() == y);
  372. /// }
  373. ///
  374. /// check(f32::INFINITY, f32::INFINITY);
  375. /// check(0.9f32, 0.0);
  376. /// check(1.0f32, 1.0);
  377. /// check(1.1f32, 1.0);
  378. /// check(-0.0f64, 0.0);
  379. /// check(-0.9f64, -0.0);
  380. /// check(-1.0f64, -1.0);
  381. /// check(-1.1f64, -1.0);
  382. /// check(f64::MIN, f64::MIN);
  383. /// ```
  384. #[inline]
  385. fn trunc(self) -> Self {
  386. let f = self.fract();
  387. if f.is_nan() {
  388. self
  389. } else {
  390. self - f
  391. }
  392. }
  393. /// Returns the fractional part of a number.
  394. ///
  395. /// # Examples
  396. ///
  397. /// ```
  398. /// use num_traits::float::FloatCore;
  399. /// use std::{f32, f64};
  400. ///
  401. /// fn check<T: FloatCore>(x: T, y: T) {
  402. /// assert!(x.fract() == y);
  403. /// }
  404. ///
  405. /// check(f32::MAX, 0.0);
  406. /// check(0.75f32, 0.75);
  407. /// check(1.0f32, 0.0);
  408. /// check(1.25f32, 0.25);
  409. /// check(-0.0f64, 0.0);
  410. /// check(-0.75f64, -0.75);
  411. /// check(-1.0f64, 0.0);
  412. /// check(-1.25f64, -0.25);
  413. /// check(f64::MIN, 0.0);
  414. /// ```
  415. #[inline]
  416. fn fract(self) -> Self {
  417. if self.is_zero() {
  418. Self::zero()
  419. } else {
  420. self % Self::one()
  421. }
  422. }
  423. /// Computes the absolute value of `self`. Returns `FloatCore::nan()` if the
  424. /// number is `FloatCore::nan()`.
  425. ///
  426. /// # Examples
  427. ///
  428. /// ```
  429. /// use num_traits::float::FloatCore;
  430. /// use std::{f32, f64};
  431. ///
  432. /// fn check<T: FloatCore>(x: T, y: T) {
  433. /// assert!(x.abs() == y);
  434. /// }
  435. ///
  436. /// check(f32::INFINITY, f32::INFINITY);
  437. /// check(1.0f32, 1.0);
  438. /// check(0.0f64, 0.0);
  439. /// check(-0.0f64, 0.0);
  440. /// check(-1.0f64, 1.0);
  441. /// check(f64::MIN, f64::MAX);
  442. /// ```
  443. #[inline]
  444. fn abs(self) -> Self {
  445. if self.is_sign_positive() {
  446. return self;
  447. }
  448. if self.is_sign_negative() {
  449. return -self;
  450. }
  451. Self::nan()
  452. }
  453. /// Returns a number that represents the sign of `self`.
  454. ///
  455. /// - `1.0` if the number is positive, `+0.0` or `FloatCore::infinity()`
  456. /// - `-1.0` if the number is negative, `-0.0` or `FloatCore::neg_infinity()`
  457. /// - `FloatCore::nan()` if the number is `FloatCore::nan()`
  458. ///
  459. /// # Examples
  460. ///
  461. /// ```
  462. /// use num_traits::float::FloatCore;
  463. /// use std::{f32, f64};
  464. ///
  465. /// fn check<T: FloatCore>(x: T, y: T) {
  466. /// assert!(x.signum() == y);
  467. /// }
  468. ///
  469. /// check(f32::INFINITY, 1.0);
  470. /// check(3.0f32, 1.0);
  471. /// check(0.0f32, 1.0);
  472. /// check(-0.0f64, -1.0);
  473. /// check(-3.0f64, -1.0);
  474. /// check(f64::MIN, -1.0);
  475. /// ```
  476. #[inline]
  477. fn signum(self) -> Self {
  478. if self.is_nan() {
  479. Self::nan()
  480. } else if self.is_sign_negative() {
  481. -Self::one()
  482. } else {
  483. Self::one()
  484. }
  485. }
  486. /// Returns `true` if `self` is positive, including `+0.0` and
  487. /// `FloatCore::infinity()`, and since Rust 1.20 also
  488. /// `FloatCore::nan()`.
  489. ///
  490. /// # Examples
  491. ///
  492. /// ```
  493. /// use num_traits::float::FloatCore;
  494. /// use std::{f32, f64};
  495. ///
  496. /// fn check<T: FloatCore>(x: T, p: bool) {
  497. /// assert!(x.is_sign_positive() == p);
  498. /// }
  499. ///
  500. /// check(f32::INFINITY, true);
  501. /// check(f32::MAX, true);
  502. /// check(0.0f32, true);
  503. /// check(-0.0f64, false);
  504. /// check(f64::NEG_INFINITY, false);
  505. /// check(f64::MIN_POSITIVE, true);
  506. /// check(-f64::NAN, false);
  507. /// ```
  508. #[inline]
  509. fn is_sign_positive(self) -> bool {
  510. !self.is_sign_negative()
  511. }
  512. /// Returns `true` if `self` is negative, including `-0.0` and
  513. /// `FloatCore::neg_infinity()`, and since Rust 1.20 also
  514. /// `-FloatCore::nan()`.
  515. ///
  516. /// # Examples
  517. ///
  518. /// ```
  519. /// use num_traits::float::FloatCore;
  520. /// use std::{f32, f64};
  521. ///
  522. /// fn check<T: FloatCore>(x: T, p: bool) {
  523. /// assert!(x.is_sign_negative() == p);
  524. /// }
  525. ///
  526. /// check(f32::INFINITY, false);
  527. /// check(f32::MAX, false);
  528. /// check(0.0f32, false);
  529. /// check(-0.0f64, true);
  530. /// check(f64::NEG_INFINITY, true);
  531. /// check(f64::MIN_POSITIVE, false);
  532. /// check(f64::NAN, false);
  533. /// ```
  534. #[inline]
  535. fn is_sign_negative(self) -> bool {
  536. let (_, _, sign) = self.integer_decode();
  537. sign < 0
  538. }
  539. /// Returns the minimum of the two numbers.
  540. ///
  541. /// If one of the arguments is NaN, then the other argument is returned.
  542. ///
  543. /// # Examples
  544. ///
  545. /// ```
  546. /// use num_traits::float::FloatCore;
  547. /// use std::{f32, f64};
  548. ///
  549. /// fn check<T: FloatCore>(x: T, y: T, min: T) {
  550. /// assert!(x.min(y) == min);
  551. /// }
  552. ///
  553. /// check(1.0f32, 2.0, 1.0);
  554. /// check(f32::NAN, 2.0, 2.0);
  555. /// check(1.0f64, -2.0, -2.0);
  556. /// check(1.0f64, f64::NAN, 1.0);
  557. /// ```
  558. #[inline]
  559. fn min(self, other: Self) -> Self {
  560. if self.is_nan() {
  561. return other;
  562. }
  563. if other.is_nan() {
  564. return self;
  565. }
  566. if self < other {
  567. self
  568. } else {
  569. other
  570. }
  571. }
  572. /// Returns the maximum of the two numbers.
  573. ///
  574. /// If one of the arguments is NaN, then the other argument is returned.
  575. ///
  576. /// # Examples
  577. ///
  578. /// ```
  579. /// use num_traits::float::FloatCore;
  580. /// use std::{f32, f64};
  581. ///
  582. /// fn check<T: FloatCore>(x: T, y: T, max: T) {
  583. /// assert!(x.max(y) == max);
  584. /// }
  585. ///
  586. /// check(1.0f32, 2.0, 2.0);
  587. /// check(1.0f32, f32::NAN, 1.0);
  588. /// check(-1.0f64, 2.0, 2.0);
  589. /// check(-1.0f64, f64::NAN, -1.0);
  590. /// ```
  591. #[inline]
  592. fn max(self, other: Self) -> Self {
  593. if self.is_nan() {
  594. return other;
  595. }
  596. if other.is_nan() {
  597. return self;
  598. }
  599. if self > other {
  600. self
  601. } else {
  602. other
  603. }
  604. }
  605. /// Returns the reciprocal (multiplicative inverse) of the number.
  606. ///
  607. /// # Examples
  608. ///
  609. /// ```
  610. /// use num_traits::float::FloatCore;
  611. /// use std::{f32, f64};
  612. ///
  613. /// fn check<T: FloatCore>(x: T, y: T) {
  614. /// assert!(x.recip() == y);
  615. /// assert!(y.recip() == x);
  616. /// }
  617. ///
  618. /// check(f32::INFINITY, 0.0);
  619. /// check(2.0f32, 0.5);
  620. /// check(-0.25f64, -4.0);
  621. /// check(-0.0f64, f64::NEG_INFINITY);
  622. /// ```
  623. #[inline]
  624. fn recip(self) -> Self {
  625. Self::one() / self
  626. }
  627. /// Raise a number to an integer power.
  628. ///
  629. /// Using this function is generally faster than using `powf`
  630. ///
  631. /// # Examples
  632. ///
  633. /// ```
  634. /// use num_traits::float::FloatCore;
  635. ///
  636. /// fn check<T: FloatCore>(x: T, exp: i32, powi: T) {
  637. /// assert!(x.powi(exp) == powi);
  638. /// }
  639. ///
  640. /// check(9.0f32, 2, 81.0);
  641. /// check(1.0f32, -2, 1.0);
  642. /// check(10.0f64, 20, 1e20);
  643. /// check(4.0f64, -2, 0.0625);
  644. /// check(-1.0f64, std::i32::MIN, 1.0);
  645. /// ```
  646. #[inline]
  647. fn powi(mut self, mut exp: i32) -> Self {
  648. if exp < 0 {
  649. exp = exp.wrapping_neg();
  650. self = self.recip();
  651. }
  652. // It should always be possible to convert a positive `i32` to a `usize`.
  653. // Note, `i32::MIN` will wrap and still be negative, so we need to convert
  654. // to `u32` without sign-extension before growing to `usize`.
  655. super::pow(self, (exp as u32).to_usize().unwrap())
  656. }
  657. /// Converts to degrees, assuming the number is in radians.
  658. ///
  659. /// # Examples
  660. ///
  661. /// ```
  662. /// use num_traits::float::FloatCore;
  663. /// use std::{f32, f64};
  664. ///
  665. /// fn check<T: FloatCore>(rad: T, deg: T) {
  666. /// assert!(rad.to_degrees() == deg);
  667. /// }
  668. ///
  669. /// check(0.0f32, 0.0);
  670. /// check(f32::consts::PI, 180.0);
  671. /// check(f64::consts::FRAC_PI_4, 45.0);
  672. /// check(f64::INFINITY, f64::INFINITY);
  673. /// ```
  674. fn to_degrees(self) -> Self;
  675. /// Converts to radians, assuming the number is in degrees.
  676. ///
  677. /// # Examples
  678. ///
  679. /// ```
  680. /// use num_traits::float::FloatCore;
  681. /// use std::{f32, f64};
  682. ///
  683. /// fn check<T: FloatCore>(deg: T, rad: T) {
  684. /// assert!(deg.to_radians() == rad);
  685. /// }
  686. ///
  687. /// check(0.0f32, 0.0);
  688. /// check(180.0, f32::consts::PI);
  689. /// check(45.0, f64::consts::FRAC_PI_4);
  690. /// check(f64::INFINITY, f64::INFINITY);
  691. /// ```
  692. fn to_radians(self) -> Self;
  693. /// Returns the mantissa, base 2 exponent, and sign as integers, respectively.
  694. /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`.
  695. ///
  696. /// # Examples
  697. ///
  698. /// ```
  699. /// use num_traits::float::FloatCore;
  700. /// use std::{f32, f64};
  701. ///
  702. /// fn check<T: FloatCore>(x: T, m: u64, e: i16, s:i8) {
  703. /// let (mantissa, exponent, sign) = x.integer_decode();
  704. /// assert_eq!(mantissa, m);
  705. /// assert_eq!(exponent, e);
  706. /// assert_eq!(sign, s);
  707. /// }
  708. ///
  709. /// check(2.0f32, 1 << 23, -22, 1);
  710. /// check(-2.0f32, 1 << 23, -22, -1);
  711. /// check(f32::INFINITY, 1 << 23, 105, 1);
  712. /// check(f64::NEG_INFINITY, 1 << 52, 972, -1);
  713. /// ```
  714. fn integer_decode(self) -> (u64, i16, i8);
  715. }
  716. impl FloatCore for f32 {
  717. constant! {
  718. infinity() -> f32::INFINITY;
  719. neg_infinity() -> f32::NEG_INFINITY;
  720. nan() -> f32::NAN;
  721. neg_zero() -> -0.0;
  722. min_value() -> f32::MIN;
  723. min_positive_value() -> f32::MIN_POSITIVE;
  724. epsilon() -> f32::EPSILON;
  725. max_value() -> f32::MAX;
  726. }
  727. #[inline]
  728. fn integer_decode(self) -> (u64, i16, i8) {
  729. integer_decode_f32(self)
  730. }
  731. #[inline]
  732. #[cfg(not(feature = "std"))]
  733. fn classify(self) -> FpCategory {
  734. const EXP_MASK: u32 = 0x7f800000;
  735. const MAN_MASK: u32 = 0x007fffff;
  736. // Safety: this identical to the implementation of f32::to_bits(),
  737. // which is only available starting at Rust 1.20
  738. let bits: u32 = unsafe { mem::transmute(self) };
  739. match (bits & MAN_MASK, bits & EXP_MASK) {
  740. (0, 0) => FpCategory::Zero,
  741. (_, 0) => FpCategory::Subnormal,
  742. (0, EXP_MASK) => FpCategory::Infinite,
  743. (_, EXP_MASK) => FpCategory::Nan,
  744. _ => FpCategory::Normal,
  745. }
  746. }
  747. #[inline]
  748. #[cfg(not(feature = "std"))]
  749. fn is_sign_negative(self) -> bool {
  750. const SIGN_MASK: u32 = 0x80000000;
  751. // Safety: this identical to the implementation of f32::to_bits(),
  752. // which is only available starting at Rust 1.20
  753. let bits: u32 = unsafe { mem::transmute(self) };
  754. bits & SIGN_MASK != 0
  755. }
  756. #[inline]
  757. #[cfg(not(feature = "std"))]
  758. fn to_degrees(self) -> Self {
  759. // Use a constant for better precision.
  760. const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
  761. self * PIS_IN_180
  762. }
  763. #[inline]
  764. #[cfg(not(feature = "std"))]
  765. fn to_radians(self) -> Self {
  766. self * (f32::consts::PI / 180.0)
  767. }
  768. #[cfg(feature = "std")]
  769. forward! {
  770. Self::is_nan(self) -> bool;
  771. Self::is_infinite(self) -> bool;
  772. Self::is_finite(self) -> bool;
  773. Self::is_normal(self) -> bool;
  774. Self::classify(self) -> FpCategory;
  775. Self::floor(self) -> Self;
  776. Self::ceil(self) -> Self;
  777. Self::round(self) -> Self;
  778. Self::trunc(self) -> Self;
  779. Self::fract(self) -> Self;
  780. Self::abs(self) -> Self;
  781. Self::signum(self) -> Self;
  782. Self::is_sign_positive(self) -> bool;
  783. Self::is_sign_negative(self) -> bool;
  784. Self::min(self, other: Self) -> Self;
  785. Self::max(self, other: Self) -> Self;
  786. Self::recip(self) -> Self;
  787. Self::powi(self, n: i32) -> Self;
  788. Self::to_degrees(self) -> Self;
  789. Self::to_radians(self) -> Self;
  790. }
  791. #[cfg(all(not(feature = "std"), feature = "libm"))]
  792. forward! {
  793. libm::floorf as floor(self) -> Self;
  794. libm::ceilf as ceil(self) -> Self;
  795. libm::roundf as round(self) -> Self;
  796. libm::truncf as trunc(self) -> Self;
  797. libm::fabsf as abs(self) -> Self;
  798. libm::fminf as min(self, other: Self) -> Self;
  799. libm::fmaxf as max(self, other: Self) -> Self;
  800. }
  801. #[cfg(all(not(feature = "std"), feature = "libm"))]
  802. #[inline]
  803. fn fract(self) -> Self {
  804. self - libm::truncf(self)
  805. }
  806. }
  807. impl FloatCore for f64 {
  808. constant! {
  809. infinity() -> f64::INFINITY;
  810. neg_infinity() -> f64::NEG_INFINITY;
  811. nan() -> f64::NAN;
  812. neg_zero() -> -0.0;
  813. min_value() -> f64::MIN;
  814. min_positive_value() -> f64::MIN_POSITIVE;
  815. epsilon() -> f64::EPSILON;
  816. max_value() -> f64::MAX;
  817. }
  818. #[inline]
  819. fn integer_decode(self) -> (u64, i16, i8) {
  820. integer_decode_f64(self)
  821. }
  822. #[inline]
  823. #[cfg(not(feature = "std"))]
  824. fn classify(self) -> FpCategory {
  825. const EXP_MASK: u64 = 0x7ff0000000000000;
  826. const MAN_MASK: u64 = 0x000fffffffffffff;
  827. // Safety: this identical to the implementation of f64::to_bits(),
  828. // which is only available starting at Rust 1.20
  829. let bits: u64 = unsafe { mem::transmute(self) };
  830. match (bits & MAN_MASK, bits & EXP_MASK) {
  831. (0, 0) => FpCategory::Zero,
  832. (_, 0) => FpCategory::Subnormal,
  833. (0, EXP_MASK) => FpCategory::Infinite,
  834. (_, EXP_MASK) => FpCategory::Nan,
  835. _ => FpCategory::Normal,
  836. }
  837. }
  838. #[inline]
  839. #[cfg(not(feature = "std"))]
  840. fn is_sign_negative(self) -> bool {
  841. const SIGN_MASK: u64 = 0x8000000000000000;
  842. // Safety: this identical to the implementation of f64::to_bits(),
  843. // which is only available starting at Rust 1.20
  844. let bits: u64 = unsafe { mem::transmute(self) };
  845. bits & SIGN_MASK != 0
  846. }
  847. #[inline]
  848. #[cfg(not(feature = "std"))]
  849. fn to_degrees(self) -> Self {
  850. // The division here is correctly rounded with respect to the true
  851. // value of 180/π. (This differs from f32, where a constant must be
  852. // used to ensure a correctly rounded result.)
  853. self * (180.0 / f64::consts::PI)
  854. }
  855. #[inline]
  856. #[cfg(not(feature = "std"))]
  857. fn to_radians(self) -> Self {
  858. self * (f64::consts::PI / 180.0)
  859. }
  860. #[cfg(feature = "std")]
  861. forward! {
  862. Self::is_nan(self) -> bool;
  863. Self::is_infinite(self) -> bool;
  864. Self::is_finite(self) -> bool;
  865. Self::is_normal(self) -> bool;
  866. Self::classify(self) -> FpCategory;
  867. Self::floor(self) -> Self;
  868. Self::ceil(self) -> Self;
  869. Self::round(self) -> Self;
  870. Self::trunc(self) -> Self;
  871. Self::fract(self) -> Self;
  872. Self::abs(self) -> Self;
  873. Self::signum(self) -> Self;
  874. Self::is_sign_positive(self) -> bool;
  875. Self::is_sign_negative(self) -> bool;
  876. Self::min(self, other: Self) -> Self;
  877. Self::max(self, other: Self) -> Self;
  878. Self::recip(self) -> Self;
  879. Self::powi(self, n: i32) -> Self;
  880. Self::to_degrees(self) -> Self;
  881. Self::to_radians(self) -> Self;
  882. }
  883. #[cfg(all(not(feature = "std"), feature = "libm"))]
  884. forward! {
  885. libm::floor as floor(self) -> Self;
  886. libm::ceil as ceil(self) -> Self;
  887. libm::round as round(self) -> Self;
  888. libm::trunc as trunc(self) -> Self;
  889. libm::fabs as abs(self) -> Self;
  890. libm::fmin as min(self, other: Self) -> Self;
  891. libm::fmax as max(self, other: Self) -> Self;
  892. }
  893. #[cfg(all(not(feature = "std"), feature = "libm"))]
  894. #[inline]
  895. fn fract(self) -> Self {
  896. self - libm::trunc(self)
  897. }
  898. }
  899. // FIXME: these doctests aren't actually helpful, because they're using and
  900. // testing the inherent methods directly, not going through `Float`.
  901. /// Generic trait for floating point numbers
  902. ///
  903. /// This trait is only available with the `std` feature, or with the `libm` feature otherwise.
  904. #[cfg(any(feature = "std", feature = "libm"))]
  905. pub trait Float: Num + Copy + NumCast + PartialOrd + Neg<Output = Self> {
  906. /// Returns the `NaN` value.
  907. ///
  908. /// ```
  909. /// use num_traits::Float;
  910. ///
  911. /// let nan: f32 = Float::nan();
  912. ///
  913. /// assert!(nan.is_nan());
  914. /// ```
  915. fn nan() -> Self;
  916. /// Returns the infinite value.
  917. ///
  918. /// ```
  919. /// use num_traits::Float;
  920. /// use std::f32;
  921. ///
  922. /// let infinity: f32 = Float::infinity();
  923. ///
  924. /// assert!(infinity.is_infinite());
  925. /// assert!(!infinity.is_finite());
  926. /// assert!(infinity > f32::MAX);
  927. /// ```
  928. fn infinity() -> Self;
  929. /// Returns the negative infinite value.
  930. ///
  931. /// ```
  932. /// use num_traits::Float;
  933. /// use std::f32;
  934. ///
  935. /// let neg_infinity: f32 = Float::neg_infinity();
  936. ///
  937. /// assert!(neg_infinity.is_infinite());
  938. /// assert!(!neg_infinity.is_finite());
  939. /// assert!(neg_infinity < f32::MIN);
  940. /// ```
  941. fn neg_infinity() -> Self;
  942. /// Returns `-0.0`.
  943. ///
  944. /// ```
  945. /// use num_traits::{Zero, Float};
  946. ///
  947. /// let inf: f32 = Float::infinity();
  948. /// let zero: f32 = Zero::zero();
  949. /// let neg_zero: f32 = Float::neg_zero();
  950. ///
  951. /// assert_eq!(zero, neg_zero);
  952. /// assert_eq!(7.0f32/inf, zero);
  953. /// assert_eq!(zero * 10.0, zero);
  954. /// ```
  955. fn neg_zero() -> Self;
  956. /// Returns the smallest finite value that this type can represent.
  957. ///
  958. /// ```
  959. /// use num_traits::Float;
  960. /// use std::f64;
  961. ///
  962. /// let x: f64 = Float::min_value();
  963. ///
  964. /// assert_eq!(x, f64::MIN);
  965. /// ```
  966. fn min_value() -> Self;
  967. /// Returns the smallest positive, normalized value that this type can represent.
  968. ///
  969. /// ```
  970. /// use num_traits::Float;
  971. /// use std::f64;
  972. ///
  973. /// let x: f64 = Float::min_positive_value();
  974. ///
  975. /// assert_eq!(x, f64::MIN_POSITIVE);
  976. /// ```
  977. fn min_positive_value() -> Self;
  978. /// Returns epsilon, a small positive value.
  979. ///
  980. /// ```
  981. /// use num_traits::Float;
  982. /// use std::f64;
  983. ///
  984. /// let x: f64 = Float::epsilon();
  985. ///
  986. /// assert_eq!(x, f64::EPSILON);
  987. /// ```
  988. ///
  989. /// # Panics
  990. ///
  991. /// The default implementation will panic if `f32::EPSILON` cannot
  992. /// be cast to `Self`.
  993. fn epsilon() -> Self {
  994. Self::from(f32::EPSILON).expect("Unable to cast from f32::EPSILON")
  995. }
  996. /// Returns the largest finite value that this type can represent.
  997. ///
  998. /// ```
  999. /// use num_traits::Float;
  1000. /// use std::f64;
  1001. ///
  1002. /// let x: f64 = Float::max_value();
  1003. /// assert_eq!(x, f64::MAX);
  1004. /// ```
  1005. fn max_value() -> Self;
  1006. /// Returns `true` if this value is `NaN` and false otherwise.
  1007. ///
  1008. /// ```
  1009. /// use num_traits::Float;
  1010. /// use std::f64;
  1011. ///
  1012. /// let nan = f64::NAN;
  1013. /// let f = 7.0;
  1014. ///
  1015. /// assert!(nan.is_nan());
  1016. /// assert!(!f.is_nan());
  1017. /// ```
  1018. fn is_nan(self) -> bool;
  1019. /// Returns `true` if this value is positive infinity or negative infinity and
  1020. /// false otherwise.
  1021. ///
  1022. /// ```
  1023. /// use num_traits::Float;
  1024. /// use std::f32;
  1025. ///
  1026. /// let f = 7.0f32;
  1027. /// let inf: f32 = Float::infinity();
  1028. /// let neg_inf: f32 = Float::neg_infinity();
  1029. /// let nan: f32 = f32::NAN;
  1030. ///
  1031. /// assert!(!f.is_infinite());
  1032. /// assert!(!nan.is_infinite());
  1033. ///
  1034. /// assert!(inf.is_infinite());
  1035. /// assert!(neg_inf.is_infinite());
  1036. /// ```
  1037. fn is_infinite(self) -> bool;
  1038. /// Returns `true` if this number is neither infinite nor `NaN`.
  1039. ///
  1040. /// ```
  1041. /// use num_traits::Float;
  1042. /// use std::f32;
  1043. ///
  1044. /// let f = 7.0f32;
  1045. /// let inf: f32 = Float::infinity();
  1046. /// let neg_inf: f32 = Float::neg_infinity();
  1047. /// let nan: f32 = f32::NAN;
  1048. ///
  1049. /// assert!(f.is_finite());
  1050. ///
  1051. /// assert!(!nan.is_finite());
  1052. /// assert!(!inf.is_finite());
  1053. /// assert!(!neg_inf.is_finite());
  1054. /// ```
  1055. fn is_finite(self) -> bool;
  1056. /// Returns `true` if the number is neither zero, infinite,
  1057. /// [subnormal][subnormal], or `NaN`.
  1058. ///
  1059. /// ```
  1060. /// use num_traits::Float;
  1061. /// use std::f32;
  1062. ///
  1063. /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
  1064. /// let max = f32::MAX;
  1065. /// let lower_than_min = 1.0e-40_f32;
  1066. /// let zero = 0.0f32;
  1067. ///
  1068. /// assert!(min.is_normal());
  1069. /// assert!(max.is_normal());
  1070. ///
  1071. /// assert!(!zero.is_normal());
  1072. /// assert!(!f32::NAN.is_normal());
  1073. /// assert!(!f32::INFINITY.is_normal());
  1074. /// // Values between `0` and `min` are Subnormal.
  1075. /// assert!(!lower_than_min.is_normal());
  1076. /// ```
  1077. /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number
  1078. fn is_normal(self) -> bool;
  1079. /// Returns the floating point category of the number. If only one property
  1080. /// is going to be tested, it is generally faster to use the specific
  1081. /// predicate instead.
  1082. ///
  1083. /// ```
  1084. /// use num_traits::Float;
  1085. /// use std::num::FpCategory;
  1086. /// use std::f32;
  1087. ///
  1088. /// let num = 12.4f32;
  1089. /// let inf = f32::INFINITY;
  1090. ///
  1091. /// assert_eq!(num.classify(), FpCategory::Normal);
  1092. /// assert_eq!(inf.classify(), FpCategory::Infinite);
  1093. /// ```
  1094. fn classify(self) -> FpCategory;
  1095. /// Returns the largest integer less than or equal to a number.
  1096. ///
  1097. /// ```
  1098. /// use num_traits::Float;
  1099. ///
  1100. /// let f = 3.99;
  1101. /// let g = 3.0;
  1102. ///
  1103. /// assert_eq!(f.floor(), 3.0);
  1104. /// assert_eq!(g.floor(), 3.0);
  1105. /// ```
  1106. fn floor(self) -> Self;
  1107. /// Returns the smallest integer greater than or equal to a number.
  1108. ///
  1109. /// ```
  1110. /// use num_traits::Float;
  1111. ///
  1112. /// let f = 3.01;
  1113. /// let g = 4.0;
  1114. ///
  1115. /// assert_eq!(f.ceil(), 4.0);
  1116. /// assert_eq!(g.ceil(), 4.0);
  1117. /// ```
  1118. fn ceil(self) -> Self;
  1119. /// Returns the nearest integer to a number. Round half-way cases away from
  1120. /// `0.0`.
  1121. ///
  1122. /// ```
  1123. /// use num_traits::Float;
  1124. ///
  1125. /// let f = 3.3;
  1126. /// let g = -3.3;
  1127. ///
  1128. /// assert_eq!(f.round(), 3.0);
  1129. /// assert_eq!(g.round(), -3.0);
  1130. /// ```
  1131. fn round(self) -> Self;
  1132. /// Return the integer part of a number.
  1133. ///
  1134. /// ```
  1135. /// use num_traits::Float;
  1136. ///
  1137. /// let f = 3.3;
  1138. /// let g = -3.7;
  1139. ///
  1140. /// assert_eq!(f.trunc(), 3.0);
  1141. /// assert_eq!(g.trunc(), -3.0);
  1142. /// ```
  1143. fn trunc(self) -> Self;
  1144. /// Returns the fractional part of a number.
  1145. ///
  1146. /// ```
  1147. /// use num_traits::Float;
  1148. ///
  1149. /// let x = 3.5;
  1150. /// let y = -3.5;
  1151. /// let abs_difference_x = (x.fract() - 0.5).abs();
  1152. /// let abs_difference_y = (y.fract() - (-0.5)).abs();
  1153. ///
  1154. /// assert!(abs_difference_x < 1e-10);
  1155. /// assert!(abs_difference_y < 1e-10);
  1156. /// ```
  1157. fn fract(self) -> Self;
  1158. /// Computes the absolute value of `self`. Returns `Float::nan()` if the
  1159. /// number is `Float::nan()`.
  1160. ///
  1161. /// ```
  1162. /// use num_traits::Float;
  1163. /// use std::f64;
  1164. ///
  1165. /// let x = 3.5;
  1166. /// let y = -3.5;
  1167. ///
  1168. /// let abs_difference_x = (x.abs() - x).abs();
  1169. /// let abs_difference_y = (y.abs() - (-y)).abs();
  1170. ///
  1171. /// assert!(abs_difference_x < 1e-10);
  1172. /// assert!(abs_difference_y < 1e-10);
  1173. ///
  1174. /// assert!(f64::NAN.abs().is_nan());
  1175. /// ```
  1176. fn abs(self) -> Self;
  1177. /// Returns a number that represents the sign of `self`.
  1178. ///
  1179. /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
  1180. /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
  1181. /// - `Float::nan()` if the number is `Float::nan()`
  1182. ///
  1183. /// ```
  1184. /// use num_traits::Float;
  1185. /// use std::f64;
  1186. ///
  1187. /// let f = 3.5;
  1188. ///
  1189. /// assert_eq!(f.signum(), 1.0);
  1190. /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
  1191. ///
  1192. /// assert!(f64::NAN.signum().is_nan());
  1193. /// ```
  1194. fn signum(self) -> Self;
  1195. /// Returns `true` if `self` is positive, including `+0.0`,
  1196. /// `Float::infinity()`, and since Rust 1.20 also `Float::nan()`.
  1197. ///
  1198. /// ```
  1199. /// use num_traits::Float;
  1200. /// use std::f64;
  1201. ///
  1202. /// let neg_nan: f64 = -f64::NAN;
  1203. ///
  1204. /// let f = 7.0;
  1205. /// let g = -7.0;
  1206. ///
  1207. /// assert!(f.is_sign_positive());
  1208. /// assert!(!g.is_sign_positive());
  1209. /// assert!(!neg_nan.is_sign_positive());
  1210. /// ```
  1211. fn is_sign_positive(self) -> bool;
  1212. /// Returns `true` if `self` is negative, including `-0.0`,
  1213. /// `Float::neg_infinity()`, and since Rust 1.20 also `-Float::nan()`.
  1214. ///
  1215. /// ```
  1216. /// use num_traits::Float;
  1217. /// use std::f64;
  1218. ///
  1219. /// let nan: f64 = f64::NAN;
  1220. ///
  1221. /// let f = 7.0;
  1222. /// let g = -7.0;
  1223. ///
  1224. /// assert!(!f.is_sign_negative());
  1225. /// assert!(g.is_sign_negative());
  1226. /// assert!(!nan.is_sign_negative());
  1227. /// ```
  1228. fn is_sign_negative(self) -> bool;
  1229. /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
  1230. /// error, yielding a more accurate result than an unfused multiply-add.
  1231. ///
  1232. /// Using `mul_add` can be more performant than an unfused multiply-add if
  1233. /// the target architecture has a dedicated `fma` CPU instruction.
  1234. ///
  1235. /// ```
  1236. /// use num_traits::Float;
  1237. ///
  1238. /// let m = 10.0;
  1239. /// let x = 4.0;
  1240. /// let b = 60.0;
  1241. ///
  1242. /// // 100.0
  1243. /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs();
  1244. ///
  1245. /// assert!(abs_difference < 1e-10);
  1246. /// ```
  1247. fn mul_add(self, a: Self, b: Self) -> Self;
  1248. /// Take the reciprocal (inverse) of a number, `1/x`.
  1249. ///
  1250. /// ```
  1251. /// use num_traits::Float;
  1252. ///
  1253. /// let x = 2.0;
  1254. /// let abs_difference = (x.recip() - (1.0/x)).abs();
  1255. ///
  1256. /// assert!(abs_difference < 1e-10);
  1257. /// ```
  1258. fn recip(self) -> Self;
  1259. /// Raise a number to an integer power.
  1260. ///
  1261. /// Using this function is generally faster than using `powf`
  1262. ///
  1263. /// ```
  1264. /// use num_traits::Float;
  1265. ///
  1266. /// let x = 2.0;
  1267. /// let abs_difference = (x.powi(2) - x*x).abs();
  1268. ///
  1269. /// assert!(abs_difference < 1e-10);
  1270. /// ```
  1271. fn powi(self, n: i32) -> Self;
  1272. /// Raise a number to a floating point power.
  1273. ///
  1274. /// ```
  1275. /// use num_traits::Float;
  1276. ///
  1277. /// let x = 2.0;
  1278. /// let abs_difference = (x.powf(2.0) - x*x).abs();
  1279. ///
  1280. /// assert!(abs_difference < 1e-10);
  1281. /// ```
  1282. fn powf(self, n: Self) -> Self;
  1283. /// Take the square root of a number.
  1284. ///
  1285. /// Returns NaN if `self` is a negative number.
  1286. ///
  1287. /// ```
  1288. /// use num_traits::Float;
  1289. ///
  1290. /// let positive = 4.0;
  1291. /// let negative = -4.0;
  1292. ///
  1293. /// let abs_difference = (positive.sqrt() - 2.0).abs();
  1294. ///
  1295. /// assert!(abs_difference < 1e-10);
  1296. /// assert!(negative.sqrt().is_nan());
  1297. /// ```
  1298. fn sqrt(self) -> Self;
  1299. /// Returns `e^(self)`, (the exponential function).
  1300. ///
  1301. /// ```
  1302. /// use num_traits::Float;
  1303. ///
  1304. /// let one = 1.0;
  1305. /// // e^1
  1306. /// let e = one.exp();
  1307. ///
  1308. /// // ln(e) - 1 == 0
  1309. /// let abs_difference = (e.ln() - 1.0).abs();
  1310. ///
  1311. /// assert!(abs_difference < 1e-10);
  1312. /// ```
  1313. fn exp(self) -> Self;
  1314. /// Returns `2^(self)`.
  1315. ///
  1316. /// ```
  1317. /// use num_traits::Float;
  1318. ///
  1319. /// let f = 2.0;
  1320. ///
  1321. /// // 2^2 - 4 == 0
  1322. /// let abs_difference = (f.exp2() - 4.0).abs();
  1323. ///
  1324. /// assert!(abs_difference < 1e-10);
  1325. /// ```
  1326. fn exp2(self) -> Self;
  1327. /// Returns the natural logarithm of the number.
  1328. ///
  1329. /// ```
  1330. /// use num_traits::Float;
  1331. ///
  1332. /// let one = 1.0;
  1333. /// // e^1
  1334. /// let e = one.exp();
  1335. ///
  1336. /// // ln(e) - 1 == 0
  1337. /// let abs_difference = (e.ln() - 1.0).abs();
  1338. ///
  1339. /// assert!(abs_difference < 1e-10);
  1340. /// ```
  1341. fn ln(self) -> Self;
  1342. /// Returns the logarithm of the number with respect to an arbitrary base.
  1343. ///
  1344. /// ```
  1345. /// use num_traits::Float;
  1346. ///
  1347. /// let ten = 10.0;
  1348. /// let two = 2.0;
  1349. ///
  1350. /// // log10(10) - 1 == 0
  1351. /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs();
  1352. ///
  1353. /// // log2(2) - 1 == 0
  1354. /// let abs_difference_2 = (two.log(2.0) - 1.0).abs();
  1355. ///
  1356. /// assert!(abs_difference_10 < 1e-10);
  1357. /// assert!(abs_difference_2 < 1e-10);
  1358. /// ```
  1359. fn log(self, base: Self) -> Self;
  1360. /// Returns the base 2 logarithm of the number.
  1361. ///
  1362. /// ```
  1363. /// use num_traits::Float;
  1364. ///
  1365. /// let two = 2.0;
  1366. ///
  1367. /// // log2(2) - 1 == 0
  1368. /// let abs_difference = (two.log2() - 1.0).abs();
  1369. ///
  1370. /// assert!(abs_difference < 1e-10);
  1371. /// ```
  1372. fn log2(self) -> Self;
  1373. /// Returns the base 10 logarithm of the number.
  1374. ///
  1375. /// ```
  1376. /// use num_traits::Float;
  1377. ///
  1378. /// let ten = 10.0;
  1379. ///
  1380. /// // log10(10) - 1 == 0
  1381. /// let abs_difference = (ten.log10() - 1.0).abs();
  1382. ///
  1383. /// assert!(abs_difference < 1e-10);
  1384. /// ```
  1385. fn log10(self) -> Self;
  1386. /// Converts radians to degrees.
  1387. ///
  1388. /// ```
  1389. /// use std::f64::consts;
  1390. ///
  1391. /// let angle = consts::PI;
  1392. ///
  1393. /// let abs_difference = (angle.to_degrees() - 180.0).abs();
  1394. ///
  1395. /// assert!(abs_difference < 1e-10);
  1396. /// ```
  1397. #[inline]
  1398. fn to_degrees(self) -> Self {
  1399. let halfpi = Self::zero().acos();
  1400. let ninety = Self::from(90u8).unwrap();
  1401. self * ninety / halfpi
  1402. }
  1403. /// Converts degrees to radians.
  1404. ///
  1405. /// ```
  1406. /// use std::f64::consts;
  1407. ///
  1408. /// let angle = 180.0_f64;
  1409. ///
  1410. /// let abs_difference = (angle.to_radians() - consts::PI).abs();
  1411. ///
  1412. /// assert!(abs_difference < 1e-10);
  1413. /// ```
  1414. #[inline]
  1415. fn to_radians(self) -> Self {
  1416. let halfpi = Self::zero().acos();
  1417. let ninety = Self::from(90u8).unwrap();
  1418. self * halfpi / ninety
  1419. }
  1420. /// Returns the maximum of the two numbers.
  1421. ///
  1422. /// ```
  1423. /// use num_traits::Float;
  1424. ///
  1425. /// let x = 1.0;
  1426. /// let y = 2.0;
  1427. ///
  1428. /// assert_eq!(x.max(y), y);
  1429. /// ```
  1430. fn max(self, other: Self) -> Self;
  1431. /// Returns the minimum of the two numbers.
  1432. ///
  1433. /// ```
  1434. /// use num_traits::Float;
  1435. ///
  1436. /// let x = 1.0;
  1437. /// let y = 2.0;
  1438. ///
  1439. /// assert_eq!(x.min(y), x);
  1440. /// ```
  1441. fn min(self, other: Self) -> Self;
  1442. /// The positive difference of two numbers.
  1443. ///
  1444. /// * If `self <= other`: `0:0`
  1445. /// * Else: `self - other`
  1446. ///
  1447. /// ```
  1448. /// use num_traits::Float;
  1449. ///
  1450. /// let x = 3.0;
  1451. /// let y = -3.0;
  1452. ///
  1453. /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
  1454. /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();
  1455. ///
  1456. /// assert!(abs_difference_x < 1e-10);
  1457. /// assert!(abs_difference_y < 1e-10);
  1458. /// ```
  1459. fn abs_sub(self, other: Self) -> Self;
  1460. /// Take the cubic root of a number.
  1461. ///
  1462. /// ```
  1463. /// use num_traits::Float;
  1464. ///
  1465. /// let x = 8.0;
  1466. ///
  1467. /// // x^(1/3) - 2 == 0
  1468. /// let abs_difference = (x.cbrt() - 2.0).abs();
  1469. ///
  1470. /// assert!(abs_difference < 1e-10);
  1471. /// ```
  1472. fn cbrt(self) -> Self;
  1473. /// Calculate the length of the hypotenuse of a right-angle triangle given
  1474. /// legs of length `x` and `y`.
  1475. ///
  1476. /// ```
  1477. /// use num_traits::Float;
  1478. ///
  1479. /// let x = 2.0;
  1480. /// let y = 3.0;
  1481. ///
  1482. /// // sqrt(x^2 + y^2)
  1483. /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
  1484. ///
  1485. /// assert!(abs_difference < 1e-10);
  1486. /// ```
  1487. fn hypot(self, other: Self) -> Self;
  1488. /// Computes the sine of a number (in radians).
  1489. ///
  1490. /// ```
  1491. /// use num_traits::Float;
  1492. /// use std::f64;
  1493. ///
  1494. /// let x = f64::consts::PI/2.0;
  1495. ///
  1496. /// let abs_difference = (x.sin() - 1.0).abs();
  1497. ///
  1498. /// assert!(abs_difference < 1e-10);
  1499. /// ```
  1500. fn sin(self) -> Self;
  1501. /// Computes the cosine of a number (in radians).
  1502. ///
  1503. /// ```
  1504. /// use num_traits::Float;
  1505. /// use std::f64;
  1506. ///
  1507. /// let x = 2.0*f64::consts::PI;
  1508. ///
  1509. /// let abs_difference = (x.cos() - 1.0).abs();
  1510. ///
  1511. /// assert!(abs_difference < 1e-10);
  1512. /// ```
  1513. fn cos(self) -> Self;
  1514. /// Computes the tangent of a number (in radians).
  1515. ///
  1516. /// ```
  1517. /// use num_traits::Float;
  1518. /// use std::f64;
  1519. ///
  1520. /// let x = f64::consts::PI/4.0;
  1521. /// let abs_difference = (x.tan() - 1.0).abs();
  1522. ///
  1523. /// assert!(abs_difference < 1e-14);
  1524. /// ```
  1525. fn tan(self) -> Self;
  1526. /// Computes the arcsine of a number. Return value is in radians in
  1527. /// the range [-pi/2, pi/2] or NaN if the number is outside the range
  1528. /// [-1, 1].
  1529. ///
  1530. /// ```
  1531. /// use num_traits::Float;
  1532. /// use std::f64;
  1533. ///
  1534. /// let f = f64::consts::PI / 2.0;
  1535. ///
  1536. /// // asin(sin(pi/2))
  1537. /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs();
  1538. ///
  1539. /// assert!(abs_difference < 1e-10);
  1540. /// ```
  1541. fn asin(self) -> Self;
  1542. /// Computes the arccosine of a number. Return value is in radians in
  1543. /// the range [0, pi] or NaN if the number is outside the range
  1544. /// [-1, 1].
  1545. ///
  1546. /// ```
  1547. /// use num_traits::Float;
  1548. /// use std::f64;
  1549. ///
  1550. /// let f = f64::consts::PI / 4.0;
  1551. ///
  1552. /// // acos(cos(pi/4))
  1553. /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs();
  1554. ///
  1555. /// assert!(abs_difference < 1e-10);
  1556. /// ```
  1557. fn acos(self) -> Self;
  1558. /// Computes the arctangent of a number. Return value is in radians in the
  1559. /// range [-pi/2, pi/2];
  1560. ///
  1561. /// ```
  1562. /// use num_traits::Float;
  1563. ///
  1564. /// let f = 1.0;
  1565. ///
  1566. /// // atan(tan(1))
  1567. /// let abs_difference = (f.tan().atan() - 1.0).abs();
  1568. ///
  1569. /// assert!(abs_difference < 1e-10);
  1570. /// ```
  1571. fn atan(self) -> Self;
  1572. /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`).
  1573. ///
  1574. /// * `x = 0`, `y = 0`: `0`
  1575. /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
  1576. /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
  1577. /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
  1578. ///
  1579. /// ```
  1580. /// use num_traits::Float;
  1581. /// use std::f64;
  1582. ///
  1583. /// let pi = f64::consts::PI;
  1584. /// // All angles from horizontal right (+x)
  1585. /// // 45 deg counter-clockwise
  1586. /// let x1 = 3.0;
  1587. /// let y1 = -3.0;
  1588. ///
  1589. /// // 135 deg clockwise
  1590. /// let x2 = -3.0;
  1591. /// let y2 = 3.0;
  1592. ///
  1593. /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs();
  1594. /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs();
  1595. ///
  1596. /// assert!(abs_difference_1 < 1e-10);
  1597. /// assert!(abs_difference_2 < 1e-10);
  1598. /// ```
  1599. fn atan2(self, other: Self) -> Self;
  1600. /// Simultaneously computes the sine and cosine of the number, `x`. Returns
  1601. /// `(sin(x), cos(x))`.
  1602. ///
  1603. /// ```
  1604. /// use num_traits::Float;
  1605. /// use std::f64;
  1606. ///
  1607. /// let x = f64::consts::PI/4.0;
  1608. /// let f = x.sin_cos();
  1609. ///
  1610. /// let abs_difference_0 = (f.0 - x.sin()).abs();
  1611. /// let abs_difference_1 = (f.1 - x.cos()).abs();
  1612. ///
  1613. /// assert!(abs_difference_0 < 1e-10);
  1614. /// assert!(abs_difference_0 < 1e-10);
  1615. /// ```
  1616. fn sin_cos(self) -> (Self, Self);
  1617. /// Returns `e^(self) - 1` in a way that is accurate even if the
  1618. /// number is close to zero.
  1619. ///
  1620. /// ```
  1621. /// use num_traits::Float;
  1622. ///
  1623. /// let x = 7.0;
  1624. ///
  1625. /// // e^(ln(7)) - 1
  1626. /// let abs_difference = (x.ln().exp_m1() - 6.0).abs();
  1627. ///
  1628. /// assert!(abs_difference < 1e-10);
  1629. /// ```
  1630. fn exp_m1(self) -> Self;
  1631. /// Returns `ln(1+n)` (natural logarithm) more accurately than if
  1632. /// the operations were performed separately.
  1633. ///
  1634. /// ```
  1635. /// use num_traits::Float;
  1636. /// use std::f64;
  1637. ///
  1638. /// let x = f64::consts::E - 1.0;
  1639. ///
  1640. /// // ln(1 + (e - 1)) == ln(e) == 1
  1641. /// let abs_difference = (x.ln_1p() - 1.0).abs();
  1642. ///
  1643. /// assert!(abs_difference < 1e-10);
  1644. /// ```
  1645. fn ln_1p(self) -> Self;
  1646. /// Hyperbolic sine function.
  1647. ///
  1648. /// ```
  1649. /// use num_traits::Float;
  1650. /// use std::f64;
  1651. ///
  1652. /// let e = f64::consts::E;
  1653. /// let x = 1.0;
  1654. ///
  1655. /// let f = x.sinh();
  1656. /// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
  1657. /// let g = (e*e - 1.0)/(2.0*e);
  1658. /// let abs_difference = (f - g).abs();
  1659. ///
  1660. /// assert!(abs_difference < 1e-10);
  1661. /// ```
  1662. fn sinh(self) -> Self;
  1663. /// Hyperbolic cosine function.
  1664. ///
  1665. /// ```
  1666. /// use num_traits::Float;
  1667. /// use std::f64;
  1668. ///
  1669. /// let e = f64::consts::E;
  1670. /// let x = 1.0;
  1671. /// let f = x.cosh();
  1672. /// // Solving cosh() at 1 gives this result
  1673. /// let g = (e*e + 1.0)/(2.0*e);
  1674. /// let abs_difference = (f - g).abs();
  1675. ///
  1676. /// // Same result
  1677. /// assert!(abs_difference < 1.0e-10);
  1678. /// ```
  1679. fn cosh(self) -> Self;
  1680. /// Hyperbolic tangent function.
  1681. ///
  1682. /// ```
  1683. /// use num_traits::Float;
  1684. /// use std::f64;
  1685. ///
  1686. /// let e = f64::consts::E;
  1687. /// let x = 1.0;
  1688. ///
  1689. /// let f = x.tanh();
  1690. /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
  1691. /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2));
  1692. /// let abs_difference = (f - g).abs();
  1693. ///
  1694. /// assert!(abs_difference < 1.0e-10);
  1695. /// ```
  1696. fn tanh(self) -> Self;
  1697. /// Inverse hyperbolic sine function.
  1698. ///
  1699. /// ```
  1700. /// use num_traits::Float;
  1701. ///
  1702. /// let x = 1.0;
  1703. /// let f = x.sinh().asinh();
  1704. ///
  1705. /// let abs_difference = (f - x).abs();
  1706. ///
  1707. /// assert!(abs_difference < 1.0e-10);
  1708. /// ```
  1709. fn asinh(self) -> Self;
  1710. /// Inverse hyperbolic cosine function.
  1711. ///
  1712. /// ```
  1713. /// use num_traits::Float;
  1714. ///
  1715. /// let x = 1.0;
  1716. /// let f = x.cosh().acosh();
  1717. ///
  1718. /// let abs_difference = (f - x).abs();
  1719. ///
  1720. /// assert!(abs_difference < 1.0e-10);
  1721. /// ```
  1722. fn acosh(self) -> Self;
  1723. /// Inverse hyperbolic tangent function.
  1724. ///
  1725. /// ```
  1726. /// use num_traits::Float;
  1727. /// use std::f64;
  1728. ///
  1729. /// let e = f64::consts::E;
  1730. /// let f = e.tanh().atanh();
  1731. ///
  1732. /// let abs_difference = (f - e).abs();
  1733. ///
  1734. /// assert!(abs_difference < 1.0e-10);
  1735. /// ```
  1736. fn atanh(self) -> Self;
  1737. /// Returns the mantissa, base 2 exponent, and sign as integers, respectively.
  1738. /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`.
  1739. ///
  1740. /// ```
  1741. /// use num_traits::Float;
  1742. ///
  1743. /// let num = 2.0f32;
  1744. ///
  1745. /// // (8388608, -22, 1)
  1746. /// let (mantissa, exponent, sign) = Float::integer_decode(num);
  1747. /// let sign_f = sign as f32;
  1748. /// let mantissa_f = mantissa as f32;
  1749. /// let exponent_f = num.powf(exponent as f32);
  1750. ///
  1751. /// // 1 * 8388608 * 2^(-22) == 2
  1752. /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs();
  1753. ///
  1754. /// assert!(abs_difference < 1e-10);
  1755. /// ```
  1756. fn integer_decode(self) -> (u64, i16, i8);
  1757. /// Returns a number composed of the magnitude of `self` and the sign of
  1758. /// `sign`.
  1759. ///
  1760. /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise
  1761. /// equal to `-self`. If `self` is a `NAN`, then a `NAN` with the sign of
  1762. /// `sign` is returned.
  1763. ///
  1764. /// # Examples
  1765. ///
  1766. /// ```
  1767. /// use num_traits::Float;
  1768. ///
  1769. /// let f = 3.5_f32;
  1770. ///
  1771. /// assert_eq!(f.copysign(0.42), 3.5_f32);
  1772. /// assert_eq!(f.copysign(-0.42), -3.5_f32);
  1773. /// assert_eq!((-f).copysign(0.42), 3.5_f32);
  1774. /// assert_eq!((-f).copysign(-0.42), -3.5_f32);
  1775. ///
  1776. /// assert!(f32::nan().copysign(1.0).is_nan());
  1777. /// ```
  1778. fn copysign(self, sign: Self) -> Self {
  1779. if self.is_sign_negative() == sign.is_sign_negative() {
  1780. self
  1781. } else {
  1782. self.neg()
  1783. }
  1784. }
  1785. }
  1786. #[cfg(feature = "std")]
  1787. macro_rules! float_impl_std {
  1788. ($T:ident $decode:ident) => {
  1789. impl Float for $T {
  1790. constant! {
  1791. nan() -> $T::NAN;
  1792. infinity() -> $T::INFINITY;
  1793. neg_infinity() -> $T::NEG_INFINITY;
  1794. neg_zero() -> -0.0;
  1795. min_value() -> $T::MIN;
  1796. min_positive_value() -> $T::MIN_POSITIVE;
  1797. epsilon() -> $T::EPSILON;
  1798. max_value() -> $T::MAX;
  1799. }
  1800. #[inline]
  1801. #[allow(deprecated)]
  1802. fn abs_sub(self, other: Self) -> Self {
  1803. <$T>::abs_sub(self, other)
  1804. }
  1805. #[inline]
  1806. fn integer_decode(self) -> (u64, i16, i8) {
  1807. $decode(self)
  1808. }
  1809. forward! {
  1810. Self::is_nan(self) -> bool;
  1811. Self::is_infinite(self) -> bool;
  1812. Self::is_finite(self) -> bool;
  1813. Self::is_normal(self) -> bool;
  1814. Self::classify(self) -> FpCategory;
  1815. Self::floor(self) -> Self;
  1816. Self::ceil(self) -> Self;
  1817. Self::round(self) -> Self;
  1818. Self::trunc(self) -> Self;
  1819. Self::fract(self) -> Self;
  1820. Self::abs(self) -> Self;
  1821. Self::signum(self) -> Self;
  1822. Self::is_sign_positive(self) -> bool;
  1823. Self::is_sign_negative(self) -> bool;
  1824. Self::mul_add(self, a: Self, b: Self) -> Self;
  1825. Self::recip(self) -> Self;
  1826. Self::powi(self, n: i32) -> Self;
  1827. Self::powf(self, n: Self) -> Self;
  1828. Self::sqrt(self) -> Self;
  1829. Self::exp(self) -> Self;
  1830. Self::exp2(self) -> Self;
  1831. Self::ln(self) -> Self;
  1832. Self::log(self, base: Self) -> Self;
  1833. Self::log2(self) -> Self;
  1834. Self::log10(self) -> Self;
  1835. Self::to_degrees(self) -> Self;
  1836. Self::to_radians(self) -> Self;
  1837. Self::max(self, other: Self) -> Self;
  1838. Self::min(self, other: Self) -> Self;
  1839. Self::cbrt(self) -> Self;
  1840. Self::hypot(self, other: Self) -> Self;
  1841. Self::sin(self) -> Self;
  1842. Self::cos(self) -> Self;
  1843. Self::tan(self) -> Self;
  1844. Self::asin(self) -> Self;
  1845. Self::acos(self) -> Self;
  1846. Self::atan(self) -> Self;
  1847. Self::atan2(self, other: Self) -> Self;
  1848. Self::sin_cos(self) -> (Self, Self);
  1849. Self::exp_m1(self) -> Self;
  1850. Self::ln_1p(self) -> Self;
  1851. Self::sinh(self) -> Self;
  1852. Self::cosh(self) -> Self;
  1853. Self::tanh(self) -> Self;
  1854. Self::asinh(self) -> Self;
  1855. Self::acosh(self) -> Self;
  1856. Self::atanh(self) -> Self;
  1857. }
  1858. #[cfg(has_copysign)]
  1859. #[inline]
  1860. fn copysign(self, sign: Self) -> Self {
  1861. Self::copysign(self, sign)
  1862. }
  1863. }
  1864. };
  1865. }
  1866. #[cfg(all(not(feature = "std"), feature = "libm"))]
  1867. macro_rules! float_impl_libm {
  1868. ($T:ident $decode:ident) => {
  1869. constant! {
  1870. nan() -> $T::NAN;
  1871. infinity() -> $T::INFINITY;
  1872. neg_infinity() -> $T::NEG_INFINITY;
  1873. neg_zero() -> -0.0;
  1874. min_value() -> $T::MIN;
  1875. min_positive_value() -> $T::MIN_POSITIVE;
  1876. epsilon() -> $T::EPSILON;
  1877. max_value() -> $T::MAX;
  1878. }
  1879. #[inline]
  1880. fn integer_decode(self) -> (u64, i16, i8) {
  1881. $decode(self)
  1882. }
  1883. #[inline]
  1884. fn fract(self) -> Self {
  1885. self - Float::trunc(self)
  1886. }
  1887. #[inline]
  1888. fn log(self, base: Self) -> Self {
  1889. self.ln() / base.ln()
  1890. }
  1891. forward! {
  1892. FloatCore::is_nan(self) -> bool;
  1893. FloatCore::is_infinite(self) -> bool;
  1894. FloatCore::is_finite(self) -> bool;
  1895. FloatCore::is_normal(self) -> bool;
  1896. FloatCore::classify(self) -> FpCategory;
  1897. FloatCore::signum(self) -> Self;
  1898. FloatCore::is_sign_positive(self) -> bool;
  1899. FloatCore::is_sign_negative(self) -> bool;
  1900. FloatCore::recip(self) -> Self;
  1901. FloatCore::powi(self, n: i32) -> Self;
  1902. FloatCore::to_degrees(self) -> Self;
  1903. FloatCore::to_radians(self) -> Self;
  1904. }
  1905. };
  1906. }
  1907. fn integer_decode_f32(f: f32) -> (u64, i16, i8) {
  1908. // Safety: this identical to the implementation of f32::to_bits(),
  1909. // which is only available starting at Rust 1.20
  1910. let bits: u32 = unsafe { mem::transmute(f) };
  1911. let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 };
  1912. let mut exponent: i16 = ((bits >> 23) & 0xff) as i16;
  1913. let mantissa = if exponent == 0 {
  1914. (bits & 0x7fffff) << 1
  1915. } else {
  1916. (bits & 0x7fffff) | 0x800000
  1917. };
  1918. // Exponent bias + mantissa shift
  1919. exponent -= 127 + 23;
  1920. (mantissa as u64, exponent, sign)
  1921. }
  1922. fn integer_decode_f64(f: f64) -> (u64, i16, i8) {
  1923. // Safety: this identical to the implementation of f64::to_bits(),
  1924. // which is only available starting at Rust 1.20
  1925. let bits: u64 = unsafe { mem::transmute(f) };
  1926. let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
  1927. let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
  1928. let mantissa = if exponent == 0 {
  1929. (bits & 0xfffffffffffff) << 1
  1930. } else {
  1931. (bits & 0xfffffffffffff) | 0x10000000000000
  1932. };
  1933. // Exponent bias + mantissa shift
  1934. exponent -= 1023 + 52;
  1935. (mantissa, exponent, sign)
  1936. }
  1937. #[cfg(feature = "std")]
  1938. float_impl_std!(f32 integer_decode_f32);
  1939. #[cfg(feature = "std")]
  1940. float_impl_std!(f64 integer_decode_f64);
  1941. #[cfg(all(not(feature = "std"), feature = "libm"))]
  1942. impl Float for f32 {
  1943. float_impl_libm!(f32 integer_decode_f32);
  1944. #[inline]
  1945. #[allow(deprecated)]
  1946. fn abs_sub(self, other: Self) -> Self {
  1947. libm::fdimf(self, other)
  1948. }
  1949. forward! {
  1950. libm::floorf as floor(self) -> Self;
  1951. libm::ceilf as ceil(self) -> Self;
  1952. libm::roundf as round(self) -> Self;
  1953. libm::truncf as trunc(self) -> Self;
  1954. libm::fabsf as abs(self) -> Self;
  1955. libm::fmaf as mul_add(self, a: Self, b: Self) -> Self;
  1956. libm::powf as powf(self, n: Self) -> Self;
  1957. libm::sqrtf as sqrt(self) -> Self;
  1958. libm::expf as exp(self) -> Self;
  1959. libm::exp2f as exp2(self) -> Self;
  1960. libm::logf as ln(self) -> Self;
  1961. libm::log2f as log2(self) -> Self;
  1962. libm::log10f as log10(self) -> Self;
  1963. libm::cbrtf as cbrt(self) -> Self;
  1964. libm::hypotf as hypot(self, other: Self) -> Self;
  1965. libm::sinf as sin(self) -> Self;
  1966. libm::cosf as cos(self) -> Self;
  1967. libm::tanf as tan(self) -> Self;
  1968. libm::asinf as asin(self) -> Self;
  1969. libm::acosf as acos(self) -> Self;
  1970. libm::atanf as atan(self) -> Self;
  1971. libm::atan2f as atan2(self, other: Self) -> Self;
  1972. libm::sincosf as sin_cos(self) -> (Self, Self);
  1973. libm::expm1f as exp_m1(self) -> Self;
  1974. libm::log1pf as ln_1p(self) -> Self;
  1975. libm::sinhf as sinh(self) -> Self;
  1976. libm::coshf as cosh(self) -> Self;
  1977. libm::tanhf as tanh(self) -> Self;
  1978. libm::asinhf as asinh(self) -> Self;
  1979. libm::acoshf as acosh(self) -> Self;
  1980. libm::atanhf as atanh(self) -> Self;
  1981. libm::fmaxf as max(self, other: Self) -> Self;
  1982. libm::fminf as min(self, other: Self) -> Self;
  1983. libm::copysignf as copysign(self, other: Self) -> Self;
  1984. }
  1985. }
  1986. #[cfg(all(not(feature = "std"), feature = "libm"))]
  1987. impl Float for f64 {
  1988. float_impl_libm!(f64 integer_decode_f64);
  1989. #[inline]
  1990. #[allow(deprecated)]
  1991. fn abs_sub(self, other: Self) -> Self {
  1992. libm::fdim(self, other)
  1993. }
  1994. forward! {
  1995. libm::floor as floor(self) -> Self;
  1996. libm::ceil as ceil(self) -> Self;
  1997. libm::round as round(self) -> Self;
  1998. libm::trunc as trunc(self) -> Self;
  1999. libm::fabs as abs(self) -> Self;
  2000. libm::fma as mul_add(self, a: Self, b: Self) -> Self;
  2001. libm::pow as powf(self, n: Self) -> Self;
  2002. libm::sqrt as sqrt(self) -> Self;
  2003. libm::exp as exp(self) -> Self;
  2004. libm::exp2 as exp2(self) -> Self;
  2005. libm::log as ln(self) -> Self;
  2006. libm::log2 as log2(self) -> Self;
  2007. libm::log10 as log10(self) -> Self;
  2008. libm::cbrt as cbrt(self) -> Self;
  2009. libm::hypot as hypot(self, other: Self) -> Self;
  2010. libm::sin as sin(self) -> Self;
  2011. libm::cos as cos(self) -> Self;
  2012. libm::tan as tan(self) -> Self;
  2013. libm::asin as asin(self) -> Self;
  2014. libm::acos as acos(self) -> Self;
  2015. libm::atan as atan(self) -> Self;
  2016. libm::atan2 as atan2(self, other: Self) -> Self;
  2017. libm::sincos as sin_cos(self) -> (Self, Self);
  2018. libm::expm1 as exp_m1(self) -> Self;
  2019. libm::log1p as ln_1p(self) -> Self;
  2020. libm::sinh as sinh(self) -> Self;
  2021. libm::cosh as cosh(self) -> Self;
  2022. libm::tanh as tanh(self) -> Self;
  2023. libm::asinh as asinh(self) -> Self;
  2024. libm::acosh as acosh(self) -> Self;
  2025. libm::atanh as atanh(self) -> Self;
  2026. libm::fmax as max(self, other: Self) -> Self;
  2027. libm::fmin as min(self, other: Self) -> Self;
  2028. libm::copysign as copysign(self, sign: Self) -> Self;
  2029. }
  2030. }
  2031. macro_rules! float_const_impl {
  2032. ($(#[$doc:meta] $constant:ident,)+) => (
  2033. #[allow(non_snake_case)]
  2034. pub trait FloatConst {
  2035. $(#[$doc] fn $constant() -> Self;)+
  2036. #[doc = "Return the full circle constant `τ`."]
  2037. #[inline]
  2038. fn TAU() -> Self where Self: Sized + Add<Self, Output = Self> {
  2039. Self::PI() + Self::PI()
  2040. }
  2041. #[doc = "Return `log10(2.0)`."]
  2042. #[inline]
  2043. fn LOG10_2() -> Self where Self: Sized + Div<Self, Output = Self> {
  2044. Self::LN_2() / Self::LN_10()
  2045. }
  2046. #[doc = "Return `log2(10.0)`."]
  2047. #[inline]
  2048. fn LOG2_10() -> Self where Self: Sized + Div<Self, Output = Self> {
  2049. Self::LN_10() / Self::LN_2()
  2050. }
  2051. }
  2052. float_const_impl! { @float f32, $($constant,)+ }
  2053. float_const_impl! { @float f64, $($constant,)+ }
  2054. );
  2055. (@float $T:ident, $($constant:ident,)+) => (
  2056. impl FloatConst for $T {
  2057. constant! {
  2058. $( $constant() -> $T::consts::$constant; )+
  2059. TAU() -> 6.28318530717958647692528676655900577;
  2060. LOG10_2() -> 0.301029995663981195213738894724493027;
  2061. LOG2_10() -> 3.32192809488736234787031942948939018;
  2062. }
  2063. }
  2064. );
  2065. }
  2066. float_const_impl! {
  2067. #[doc = "Return Euler’s number."]
  2068. E,
  2069. #[doc = "Return `1.0 / π`."]
  2070. FRAC_1_PI,
  2071. #[doc = "Return `1.0 / sqrt(2.0)`."]
  2072. FRAC_1_SQRT_2,
  2073. #[doc = "Return `2.0 / π`."]
  2074. FRAC_2_PI,
  2075. #[doc = "Return `2.0 / sqrt(π)`."]
  2076. FRAC_2_SQRT_PI,
  2077. #[doc = "Return `π / 2.0`."]
  2078. FRAC_PI_2,
  2079. #[doc = "Return `π / 3.0`."]
  2080. FRAC_PI_3,
  2081. #[doc = "Return `π / 4.0`."]
  2082. FRAC_PI_4,
  2083. #[doc = "Return `π / 6.0`."]
  2084. FRAC_PI_6,
  2085. #[doc = "Return `π / 8.0`."]
  2086. FRAC_PI_8,
  2087. #[doc = "Return `ln(10.0)`."]
  2088. LN_10,
  2089. #[doc = "Return `ln(2.0)`."]
  2090. LN_2,
  2091. #[doc = "Return `log10(e)`."]
  2092. LOG10_E,
  2093. #[doc = "Return `log2(e)`."]
  2094. LOG2_E,
  2095. #[doc = "Return Archimedes’ constant `π`."]
  2096. PI,
  2097. #[doc = "Return `sqrt(2.0)`."]
  2098. SQRT_2,
  2099. }
  2100. #[cfg(test)]
  2101. mod tests {
  2102. use core::f64::consts;
  2103. const DEG_RAD_PAIRS: [(f64, f64); 7] = [
  2104. (0.0, 0.),
  2105. (22.5, consts::FRAC_PI_8),
  2106. (30.0, consts::FRAC_PI_6),
  2107. (45.0, consts::FRAC_PI_4),
  2108. (60.0, consts::FRAC_PI_3),
  2109. (90.0, consts::FRAC_PI_2),
  2110. (180.0, consts::PI),
  2111. ];
  2112. #[test]
  2113. fn convert_deg_rad() {
  2114. use float::FloatCore;
  2115. for &(deg, rad) in &DEG_RAD_PAIRS {
  2116. assert!((FloatCore::to_degrees(rad) - deg).abs() < 1e-6);
  2117. assert!((FloatCore::to_radians(deg) - rad).abs() < 1e-6);
  2118. let (deg, rad) = (deg as f32, rad as f32);
  2119. assert!((FloatCore::to_degrees(rad) - deg).abs() < 1e-5);
  2120. assert!((FloatCore::to_radians(deg) - rad).abs() < 1e-5);
  2121. }
  2122. }
  2123. #[cfg(any(feature = "std", feature = "libm"))]
  2124. #[test]
  2125. fn convert_deg_rad_std() {
  2126. for &(deg, rad) in &DEG_RAD_PAIRS {
  2127. use Float;
  2128. assert!((Float::to_degrees(rad) - deg).abs() < 1e-6);
  2129. assert!((Float::to_radians(deg) - rad).abs() < 1e-6);
  2130. let (deg, rad) = (deg as f32, rad as f32);
  2131. assert!((Float::to_degrees(rad) - deg).abs() < 1e-5);
  2132. assert!((Float::to_radians(deg) - rad).abs() < 1e-5);
  2133. }
  2134. }
  2135. #[test]
  2136. // This fails with the forwarded `std` implementation in Rust 1.8.
  2137. // To avoid the failure, the test is limited to `no_std` builds.
  2138. #[cfg(not(feature = "std"))]
  2139. fn to_degrees_rounding() {
  2140. use float::FloatCore;
  2141. assert_eq!(
  2142. FloatCore::to_degrees(1_f32),
  2143. 57.2957795130823208767981548141051703
  2144. );
  2145. }
  2146. #[test]
  2147. #[cfg(any(feature = "std", feature = "libm"))]
  2148. fn extra_logs() {
  2149. use float::{Float, FloatConst};
  2150. fn check<F: Float + FloatConst>(diff: F) {
  2151. let _2 = F::from(2.0).unwrap();
  2152. assert!((F::LOG10_2() - F::log10(_2)).abs() < diff);
  2153. assert!((F::LOG10_2() - F::LN_2() / F::LN_10()).abs() < diff);
  2154. let _10 = F::from(10.0).unwrap();
  2155. assert!((F::LOG2_10() - F::log2(_10)).abs() < diff);
  2156. assert!((F::LOG2_10() - F::LN_10() / F::LN_2()).abs() < diff);
  2157. }
  2158. check::<f32>(1e-6);
  2159. check::<f64>(1e-12);
  2160. }
  2161. #[test]
  2162. #[cfg(any(feature = "std", feature = "libm"))]
  2163. fn copysign() {
  2164. use float::Float;
  2165. test_copysign_generic(2.0_f32, -2.0_f32, f32::nan());
  2166. test_copysign_generic(2.0_f64, -2.0_f64, f64::nan());
  2167. test_copysignf(2.0_f32, -2.0_f32, f32::nan());
  2168. }
  2169. #[cfg(any(feature = "std", feature = "libm"))]
  2170. fn test_copysignf(p: f32, n: f32, nan: f32) {
  2171. use core::ops::Neg;
  2172. use float::Float;
  2173. assert!(p.is_sign_positive());
  2174. assert!(n.is_sign_negative());
  2175. assert!(nan.is_nan());
  2176. assert_eq!(p, Float::copysign(p, p));
  2177. assert_eq!(p.neg(), Float::copysign(p, n));
  2178. assert_eq!(n, Float::copysign(n, n));
  2179. assert_eq!(n.neg(), Float::copysign(n, p));
  2180. // FIXME: is_sign... only works on NaN starting in Rust 1.20
  2181. // assert!(Float::copysign(nan, p).is_sign_positive());
  2182. // assert!(Float::copysign(nan, n).is_sign_negative());
  2183. }
  2184. #[cfg(any(feature = "std", feature = "libm"))]
  2185. fn test_copysign_generic<F: ::float::Float + ::core::fmt::Debug>(p: F, n: F, nan: F) {
  2186. assert!(p.is_sign_positive());
  2187. assert!(n.is_sign_negative());
  2188. assert!(nan.is_nan());
  2189. assert_eq!(p, p.copysign(p));
  2190. assert_eq!(p.neg(), p.copysign(n));
  2191. assert_eq!(n, n.copysign(n));
  2192. assert_eq!(n.neg(), n.copysign(p));
  2193. // FIXME: is_sign... only works on NaN starting in Rust 1.20
  2194. // assert!(nan.copysign(p).is_sign_positive());
  2195. // assert!(nan.copysign(n).is_sign_negative());
  2196. }
  2197. }