float.rs 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390
  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 to_degrees(self) -> Self {
  750. // Use a constant for better precision.
  751. const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
  752. self * PIS_IN_180
  753. }
  754. #[inline]
  755. #[cfg(not(feature = "std"))]
  756. fn to_radians(self) -> Self {
  757. self * (f32::consts::PI / 180.0)
  758. }
  759. #[cfg(feature = "std")]
  760. forward! {
  761. Self::is_nan(self) -> bool;
  762. Self::is_infinite(self) -> bool;
  763. Self::is_finite(self) -> bool;
  764. Self::is_normal(self) -> bool;
  765. Self::classify(self) -> FpCategory;
  766. Self::floor(self) -> Self;
  767. Self::ceil(self) -> Self;
  768. Self::round(self) -> Self;
  769. Self::trunc(self) -> Self;
  770. Self::fract(self) -> Self;
  771. Self::abs(self) -> Self;
  772. Self::signum(self) -> Self;
  773. Self::is_sign_positive(self) -> bool;
  774. Self::is_sign_negative(self) -> bool;
  775. Self::min(self, other: Self) -> Self;
  776. Self::max(self, other: Self) -> Self;
  777. Self::recip(self) -> Self;
  778. Self::powi(self, n: i32) -> Self;
  779. Self::to_degrees(self) -> Self;
  780. Self::to_radians(self) -> Self;
  781. }
  782. }
  783. impl FloatCore for f64 {
  784. constant! {
  785. infinity() -> f64::INFINITY;
  786. neg_infinity() -> f64::NEG_INFINITY;
  787. nan() -> f64::NAN;
  788. neg_zero() -> -0.0;
  789. min_value() -> f64::MIN;
  790. min_positive_value() -> f64::MIN_POSITIVE;
  791. epsilon() -> f64::EPSILON;
  792. max_value() -> f64::MAX;
  793. }
  794. #[inline]
  795. fn integer_decode(self) -> (u64, i16, i8) {
  796. integer_decode_f64(self)
  797. }
  798. #[inline]
  799. #[cfg(not(feature = "std"))]
  800. fn classify(self) -> FpCategory {
  801. const EXP_MASK: u64 = 0x7ff0000000000000;
  802. const MAN_MASK: u64 = 0x000fffffffffffff;
  803. // Safety: this identical to the implementation of f64::to_bits(),
  804. // which is only available starting at Rust 1.20
  805. let bits: u64 = unsafe { mem::transmute(self) };
  806. match (bits & MAN_MASK, bits & EXP_MASK) {
  807. (0, 0) => FpCategory::Zero,
  808. (_, 0) => FpCategory::Subnormal,
  809. (0, EXP_MASK) => FpCategory::Infinite,
  810. (_, EXP_MASK) => FpCategory::Nan,
  811. _ => FpCategory::Normal,
  812. }
  813. }
  814. #[inline]
  815. #[cfg(not(feature = "std"))]
  816. fn to_degrees(self) -> Self {
  817. // The division here is correctly rounded with respect to the true
  818. // value of 180/π. (This differs from f32, where a constant must be
  819. // used to ensure a correctly rounded result.)
  820. self * (180.0 / f64::consts::PI)
  821. }
  822. #[inline]
  823. #[cfg(not(feature = "std"))]
  824. fn to_radians(self) -> Self {
  825. self * (f64::consts::PI / 180.0)
  826. }
  827. #[cfg(feature = "std")]
  828. forward! {
  829. Self::is_nan(self) -> bool;
  830. Self::is_infinite(self) -> bool;
  831. Self::is_finite(self) -> bool;
  832. Self::is_normal(self) -> bool;
  833. Self::classify(self) -> FpCategory;
  834. Self::floor(self) -> Self;
  835. Self::ceil(self) -> Self;
  836. Self::round(self) -> Self;
  837. Self::trunc(self) -> Self;
  838. Self::fract(self) -> Self;
  839. Self::abs(self) -> Self;
  840. Self::signum(self) -> Self;
  841. Self::is_sign_positive(self) -> bool;
  842. Self::is_sign_negative(self) -> bool;
  843. Self::min(self, other: Self) -> Self;
  844. Self::max(self, other: Self) -> Self;
  845. Self::recip(self) -> Self;
  846. Self::powi(self, n: i32) -> Self;
  847. Self::to_degrees(self) -> Self;
  848. Self::to_radians(self) -> Self;
  849. }
  850. }
  851. // FIXME: these doctests aren't actually helpful, because they're using and
  852. // testing the inherent methods directly, not going through `Float`.
  853. /// Generic trait for floating point numbers
  854. ///
  855. /// This trait is only available with the `std` feature, or with the `libm` feature otherwise.
  856. #[cfg(any(feature = "std", feature = "libm"))]
  857. pub trait Float: Num + Copy + NumCast + PartialOrd + Neg<Output = Self> {
  858. /// Returns the `NaN` value.
  859. ///
  860. /// ```
  861. /// use num_traits::Float;
  862. ///
  863. /// let nan: f32 = Float::nan();
  864. ///
  865. /// assert!(nan.is_nan());
  866. /// ```
  867. fn nan() -> Self;
  868. /// Returns the infinite value.
  869. ///
  870. /// ```
  871. /// use num_traits::Float;
  872. /// use std::f32;
  873. ///
  874. /// let infinity: f32 = Float::infinity();
  875. ///
  876. /// assert!(infinity.is_infinite());
  877. /// assert!(!infinity.is_finite());
  878. /// assert!(infinity > f32::MAX);
  879. /// ```
  880. fn infinity() -> Self;
  881. /// Returns the negative infinite value.
  882. ///
  883. /// ```
  884. /// use num_traits::Float;
  885. /// use std::f32;
  886. ///
  887. /// let neg_infinity: f32 = Float::neg_infinity();
  888. ///
  889. /// assert!(neg_infinity.is_infinite());
  890. /// assert!(!neg_infinity.is_finite());
  891. /// assert!(neg_infinity < f32::MIN);
  892. /// ```
  893. fn neg_infinity() -> Self;
  894. /// Returns `-0.0`.
  895. ///
  896. /// ```
  897. /// use num_traits::{Zero, Float};
  898. ///
  899. /// let inf: f32 = Float::infinity();
  900. /// let zero: f32 = Zero::zero();
  901. /// let neg_zero: f32 = Float::neg_zero();
  902. ///
  903. /// assert_eq!(zero, neg_zero);
  904. /// assert_eq!(7.0f32/inf, zero);
  905. /// assert_eq!(zero * 10.0, zero);
  906. /// ```
  907. fn neg_zero() -> Self;
  908. /// Returns the smallest finite value that this type can represent.
  909. ///
  910. /// ```
  911. /// use num_traits::Float;
  912. /// use std::f64;
  913. ///
  914. /// let x: f64 = Float::min_value();
  915. ///
  916. /// assert_eq!(x, f64::MIN);
  917. /// ```
  918. fn min_value() -> Self;
  919. /// Returns the smallest positive, normalized value that this type can represent.
  920. ///
  921. /// ```
  922. /// use num_traits::Float;
  923. /// use std::f64;
  924. ///
  925. /// let x: f64 = Float::min_positive_value();
  926. ///
  927. /// assert_eq!(x, f64::MIN_POSITIVE);
  928. /// ```
  929. fn min_positive_value() -> Self;
  930. /// Returns epsilon, a small positive value.
  931. ///
  932. /// ```
  933. /// use num_traits::Float;
  934. /// use std::f64;
  935. ///
  936. /// let x: f64 = Float::epsilon();
  937. ///
  938. /// assert_eq!(x, f64::EPSILON);
  939. /// ```
  940. ///
  941. /// # Panics
  942. ///
  943. /// The default implementation will panic if `f32::EPSILON` cannot
  944. /// be cast to `Self`.
  945. fn epsilon() -> Self {
  946. Self::from(f32::EPSILON).expect("Unable to cast from f32::EPSILON")
  947. }
  948. /// Returns the largest finite value that this type can represent.
  949. ///
  950. /// ```
  951. /// use num_traits::Float;
  952. /// use std::f64;
  953. ///
  954. /// let x: f64 = Float::max_value();
  955. /// assert_eq!(x, f64::MAX);
  956. /// ```
  957. fn max_value() -> Self;
  958. /// Returns `true` if this value is `NaN` and false otherwise.
  959. ///
  960. /// ```
  961. /// use num_traits::Float;
  962. /// use std::f64;
  963. ///
  964. /// let nan = f64::NAN;
  965. /// let f = 7.0;
  966. ///
  967. /// assert!(nan.is_nan());
  968. /// assert!(!f.is_nan());
  969. /// ```
  970. fn is_nan(self) -> bool;
  971. /// Returns `true` if this value is positive infinity or negative infinity and
  972. /// false otherwise.
  973. ///
  974. /// ```
  975. /// use num_traits::Float;
  976. /// use std::f32;
  977. ///
  978. /// let f = 7.0f32;
  979. /// let inf: f32 = Float::infinity();
  980. /// let neg_inf: f32 = Float::neg_infinity();
  981. /// let nan: f32 = f32::NAN;
  982. ///
  983. /// assert!(!f.is_infinite());
  984. /// assert!(!nan.is_infinite());
  985. ///
  986. /// assert!(inf.is_infinite());
  987. /// assert!(neg_inf.is_infinite());
  988. /// ```
  989. fn is_infinite(self) -> bool;
  990. /// Returns `true` if this number is neither infinite nor `NaN`.
  991. ///
  992. /// ```
  993. /// use num_traits::Float;
  994. /// use std::f32;
  995. ///
  996. /// let f = 7.0f32;
  997. /// let inf: f32 = Float::infinity();
  998. /// let neg_inf: f32 = Float::neg_infinity();
  999. /// let nan: f32 = f32::NAN;
  1000. ///
  1001. /// assert!(f.is_finite());
  1002. ///
  1003. /// assert!(!nan.is_finite());
  1004. /// assert!(!inf.is_finite());
  1005. /// assert!(!neg_inf.is_finite());
  1006. /// ```
  1007. fn is_finite(self) -> bool;
  1008. /// Returns `true` if the number is neither zero, infinite,
  1009. /// [subnormal][subnormal], or `NaN`.
  1010. ///
  1011. /// ```
  1012. /// use num_traits::Float;
  1013. /// use std::f32;
  1014. ///
  1015. /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
  1016. /// let max = f32::MAX;
  1017. /// let lower_than_min = 1.0e-40_f32;
  1018. /// let zero = 0.0f32;
  1019. ///
  1020. /// assert!(min.is_normal());
  1021. /// assert!(max.is_normal());
  1022. ///
  1023. /// assert!(!zero.is_normal());
  1024. /// assert!(!f32::NAN.is_normal());
  1025. /// assert!(!f32::INFINITY.is_normal());
  1026. /// // Values between `0` and `min` are Subnormal.
  1027. /// assert!(!lower_than_min.is_normal());
  1028. /// ```
  1029. /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number
  1030. fn is_normal(self) -> bool;
  1031. /// Returns the floating point category of the number. If only one property
  1032. /// is going to be tested, it is generally faster to use the specific
  1033. /// predicate instead.
  1034. ///
  1035. /// ```
  1036. /// use num_traits::Float;
  1037. /// use std::num::FpCategory;
  1038. /// use std::f32;
  1039. ///
  1040. /// let num = 12.4f32;
  1041. /// let inf = f32::INFINITY;
  1042. ///
  1043. /// assert_eq!(num.classify(), FpCategory::Normal);
  1044. /// assert_eq!(inf.classify(), FpCategory::Infinite);
  1045. /// ```
  1046. fn classify(self) -> FpCategory;
  1047. /// Returns the largest integer less than or equal to a number.
  1048. ///
  1049. /// ```
  1050. /// use num_traits::Float;
  1051. ///
  1052. /// let f = 3.99;
  1053. /// let g = 3.0;
  1054. ///
  1055. /// assert_eq!(f.floor(), 3.0);
  1056. /// assert_eq!(g.floor(), 3.0);
  1057. /// ```
  1058. fn floor(self) -> Self;
  1059. /// Returns the smallest integer greater than or equal to a number.
  1060. ///
  1061. /// ```
  1062. /// use num_traits::Float;
  1063. ///
  1064. /// let f = 3.01;
  1065. /// let g = 4.0;
  1066. ///
  1067. /// assert_eq!(f.ceil(), 4.0);
  1068. /// assert_eq!(g.ceil(), 4.0);
  1069. /// ```
  1070. fn ceil(self) -> Self;
  1071. /// Returns the nearest integer to a number. Round half-way cases away from
  1072. /// `0.0`.
  1073. ///
  1074. /// ```
  1075. /// use num_traits::Float;
  1076. ///
  1077. /// let f = 3.3;
  1078. /// let g = -3.3;
  1079. ///
  1080. /// assert_eq!(f.round(), 3.0);
  1081. /// assert_eq!(g.round(), -3.0);
  1082. /// ```
  1083. fn round(self) -> Self;
  1084. /// Return the integer part of a number.
  1085. ///
  1086. /// ```
  1087. /// use num_traits::Float;
  1088. ///
  1089. /// let f = 3.3;
  1090. /// let g = -3.7;
  1091. ///
  1092. /// assert_eq!(f.trunc(), 3.0);
  1093. /// assert_eq!(g.trunc(), -3.0);
  1094. /// ```
  1095. fn trunc(self) -> Self;
  1096. /// Returns the fractional part of a number.
  1097. ///
  1098. /// ```
  1099. /// use num_traits::Float;
  1100. ///
  1101. /// let x = 3.5;
  1102. /// let y = -3.5;
  1103. /// let abs_difference_x = (x.fract() - 0.5).abs();
  1104. /// let abs_difference_y = (y.fract() - (-0.5)).abs();
  1105. ///
  1106. /// assert!(abs_difference_x < 1e-10);
  1107. /// assert!(abs_difference_y < 1e-10);
  1108. /// ```
  1109. fn fract(self) -> Self;
  1110. /// Computes the absolute value of `self`. Returns `Float::nan()` if the
  1111. /// number is `Float::nan()`.
  1112. ///
  1113. /// ```
  1114. /// use num_traits::Float;
  1115. /// use std::f64;
  1116. ///
  1117. /// let x = 3.5;
  1118. /// let y = -3.5;
  1119. ///
  1120. /// let abs_difference_x = (x.abs() - x).abs();
  1121. /// let abs_difference_y = (y.abs() - (-y)).abs();
  1122. ///
  1123. /// assert!(abs_difference_x < 1e-10);
  1124. /// assert!(abs_difference_y < 1e-10);
  1125. ///
  1126. /// assert!(f64::NAN.abs().is_nan());
  1127. /// ```
  1128. fn abs(self) -> Self;
  1129. /// Returns a number that represents the sign of `self`.
  1130. ///
  1131. /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
  1132. /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
  1133. /// - `Float::nan()` if the number is `Float::nan()`
  1134. ///
  1135. /// ```
  1136. /// use num_traits::Float;
  1137. /// use std::f64;
  1138. ///
  1139. /// let f = 3.5;
  1140. ///
  1141. /// assert_eq!(f.signum(), 1.0);
  1142. /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
  1143. ///
  1144. /// assert!(f64::NAN.signum().is_nan());
  1145. /// ```
  1146. fn signum(self) -> Self;
  1147. /// Returns `true` if `self` is positive, including `+0.0`,
  1148. /// `Float::infinity()`, and since Rust 1.20 also `Float::nan()`.
  1149. ///
  1150. /// ```
  1151. /// use num_traits::Float;
  1152. /// use std::f64;
  1153. ///
  1154. /// let neg_nan: f64 = -f64::NAN;
  1155. ///
  1156. /// let f = 7.0;
  1157. /// let g = -7.0;
  1158. ///
  1159. /// assert!(f.is_sign_positive());
  1160. /// assert!(!g.is_sign_positive());
  1161. /// assert!(!neg_nan.is_sign_positive());
  1162. /// ```
  1163. fn is_sign_positive(self) -> bool;
  1164. /// Returns `true` if `self` is negative, including `-0.0`,
  1165. /// `Float::neg_infinity()`, and since Rust 1.20 also `-Float::nan()`.
  1166. ///
  1167. /// ```
  1168. /// use num_traits::Float;
  1169. /// use std::f64;
  1170. ///
  1171. /// let nan: f64 = f64::NAN;
  1172. ///
  1173. /// let f = 7.0;
  1174. /// let g = -7.0;
  1175. ///
  1176. /// assert!(!f.is_sign_negative());
  1177. /// assert!(g.is_sign_negative());
  1178. /// assert!(!nan.is_sign_negative());
  1179. /// ```
  1180. fn is_sign_negative(self) -> bool;
  1181. /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
  1182. /// error, yielding a more accurate result than an unfused multiply-add.
  1183. ///
  1184. /// Using `mul_add` can be more performant than an unfused multiply-add if
  1185. /// the target architecture has a dedicated `fma` CPU instruction.
  1186. ///
  1187. /// ```
  1188. /// use num_traits::Float;
  1189. ///
  1190. /// let m = 10.0;
  1191. /// let x = 4.0;
  1192. /// let b = 60.0;
  1193. ///
  1194. /// // 100.0
  1195. /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs();
  1196. ///
  1197. /// assert!(abs_difference < 1e-10);
  1198. /// ```
  1199. fn mul_add(self, a: Self, b: Self) -> Self;
  1200. /// Take the reciprocal (inverse) of a number, `1/x`.
  1201. ///
  1202. /// ```
  1203. /// use num_traits::Float;
  1204. ///
  1205. /// let x = 2.0;
  1206. /// let abs_difference = (x.recip() - (1.0/x)).abs();
  1207. ///
  1208. /// assert!(abs_difference < 1e-10);
  1209. /// ```
  1210. fn recip(self) -> Self;
  1211. /// Raise a number to an integer power.
  1212. ///
  1213. /// Using this function is generally faster than using `powf`
  1214. ///
  1215. /// ```
  1216. /// use num_traits::Float;
  1217. ///
  1218. /// let x = 2.0;
  1219. /// let abs_difference = (x.powi(2) - x*x).abs();
  1220. ///
  1221. /// assert!(abs_difference < 1e-10);
  1222. /// ```
  1223. fn powi(self, n: i32) -> Self;
  1224. /// Raise a number to a floating point power.
  1225. ///
  1226. /// ```
  1227. /// use num_traits::Float;
  1228. ///
  1229. /// let x = 2.0;
  1230. /// let abs_difference = (x.powf(2.0) - x*x).abs();
  1231. ///
  1232. /// assert!(abs_difference < 1e-10);
  1233. /// ```
  1234. fn powf(self, n: Self) -> Self;
  1235. /// Take the square root of a number.
  1236. ///
  1237. /// Returns NaN if `self` is a negative number.
  1238. ///
  1239. /// ```
  1240. /// use num_traits::Float;
  1241. ///
  1242. /// let positive = 4.0;
  1243. /// let negative = -4.0;
  1244. ///
  1245. /// let abs_difference = (positive.sqrt() - 2.0).abs();
  1246. ///
  1247. /// assert!(abs_difference < 1e-10);
  1248. /// assert!(negative.sqrt().is_nan());
  1249. /// ```
  1250. fn sqrt(self) -> Self;
  1251. /// Returns `e^(self)`, (the exponential function).
  1252. ///
  1253. /// ```
  1254. /// use num_traits::Float;
  1255. ///
  1256. /// let one = 1.0;
  1257. /// // e^1
  1258. /// let e = one.exp();
  1259. ///
  1260. /// // ln(e) - 1 == 0
  1261. /// let abs_difference = (e.ln() - 1.0).abs();
  1262. ///
  1263. /// assert!(abs_difference < 1e-10);
  1264. /// ```
  1265. fn exp(self) -> Self;
  1266. /// Returns `2^(self)`.
  1267. ///
  1268. /// ```
  1269. /// use num_traits::Float;
  1270. ///
  1271. /// let f = 2.0;
  1272. ///
  1273. /// // 2^2 - 4 == 0
  1274. /// let abs_difference = (f.exp2() - 4.0).abs();
  1275. ///
  1276. /// assert!(abs_difference < 1e-10);
  1277. /// ```
  1278. fn exp2(self) -> Self;
  1279. /// Returns the natural logarithm of the number.
  1280. ///
  1281. /// ```
  1282. /// use num_traits::Float;
  1283. ///
  1284. /// let one = 1.0;
  1285. /// // e^1
  1286. /// let e = one.exp();
  1287. ///
  1288. /// // ln(e) - 1 == 0
  1289. /// let abs_difference = (e.ln() - 1.0).abs();
  1290. ///
  1291. /// assert!(abs_difference < 1e-10);
  1292. /// ```
  1293. fn ln(self) -> Self;
  1294. /// Returns the logarithm of the number with respect to an arbitrary base.
  1295. ///
  1296. /// ```
  1297. /// use num_traits::Float;
  1298. ///
  1299. /// let ten = 10.0;
  1300. /// let two = 2.0;
  1301. ///
  1302. /// // log10(10) - 1 == 0
  1303. /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs();
  1304. ///
  1305. /// // log2(2) - 1 == 0
  1306. /// let abs_difference_2 = (two.log(2.0) - 1.0).abs();
  1307. ///
  1308. /// assert!(abs_difference_10 < 1e-10);
  1309. /// assert!(abs_difference_2 < 1e-10);
  1310. /// ```
  1311. fn log(self, base: Self) -> Self;
  1312. /// Returns the base 2 logarithm of the number.
  1313. ///
  1314. /// ```
  1315. /// use num_traits::Float;
  1316. ///
  1317. /// let two = 2.0;
  1318. ///
  1319. /// // log2(2) - 1 == 0
  1320. /// let abs_difference = (two.log2() - 1.0).abs();
  1321. ///
  1322. /// assert!(abs_difference < 1e-10);
  1323. /// ```
  1324. fn log2(self) -> Self;
  1325. /// Returns the base 10 logarithm of the number.
  1326. ///
  1327. /// ```
  1328. /// use num_traits::Float;
  1329. ///
  1330. /// let ten = 10.0;
  1331. ///
  1332. /// // log10(10) - 1 == 0
  1333. /// let abs_difference = (ten.log10() - 1.0).abs();
  1334. ///
  1335. /// assert!(abs_difference < 1e-10);
  1336. /// ```
  1337. fn log10(self) -> Self;
  1338. /// Converts radians to degrees.
  1339. ///
  1340. /// ```
  1341. /// use std::f64::consts;
  1342. ///
  1343. /// let angle = consts::PI;
  1344. ///
  1345. /// let abs_difference = (angle.to_degrees() - 180.0).abs();
  1346. ///
  1347. /// assert!(abs_difference < 1e-10);
  1348. /// ```
  1349. #[inline]
  1350. fn to_degrees(self) -> Self {
  1351. let halfpi = Self::zero().acos();
  1352. let ninety = Self::from(90u8).unwrap();
  1353. self * ninety / halfpi
  1354. }
  1355. /// Converts degrees to radians.
  1356. ///
  1357. /// ```
  1358. /// use std::f64::consts;
  1359. ///
  1360. /// let angle = 180.0_f64;
  1361. ///
  1362. /// let abs_difference = (angle.to_radians() - consts::PI).abs();
  1363. ///
  1364. /// assert!(abs_difference < 1e-10);
  1365. /// ```
  1366. #[inline]
  1367. fn to_radians(self) -> Self {
  1368. let halfpi = Self::zero().acos();
  1369. let ninety = Self::from(90u8).unwrap();
  1370. self * halfpi / ninety
  1371. }
  1372. /// Returns the maximum of the two numbers.
  1373. ///
  1374. /// ```
  1375. /// use num_traits::Float;
  1376. ///
  1377. /// let x = 1.0;
  1378. /// let y = 2.0;
  1379. ///
  1380. /// assert_eq!(x.max(y), y);
  1381. /// ```
  1382. fn max(self, other: Self) -> Self;
  1383. /// Returns the minimum of the two numbers.
  1384. ///
  1385. /// ```
  1386. /// use num_traits::Float;
  1387. ///
  1388. /// let x = 1.0;
  1389. /// let y = 2.0;
  1390. ///
  1391. /// assert_eq!(x.min(y), x);
  1392. /// ```
  1393. fn min(self, other: Self) -> Self;
  1394. /// The positive difference of two numbers.
  1395. ///
  1396. /// * If `self <= other`: `0:0`
  1397. /// * Else: `self - other`
  1398. ///
  1399. /// ```
  1400. /// use num_traits::Float;
  1401. ///
  1402. /// let x = 3.0;
  1403. /// let y = -3.0;
  1404. ///
  1405. /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
  1406. /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();
  1407. ///
  1408. /// assert!(abs_difference_x < 1e-10);
  1409. /// assert!(abs_difference_y < 1e-10);
  1410. /// ```
  1411. fn abs_sub(self, other: Self) -> Self;
  1412. /// Take the cubic root of a number.
  1413. ///
  1414. /// ```
  1415. /// use num_traits::Float;
  1416. ///
  1417. /// let x = 8.0;
  1418. ///
  1419. /// // x^(1/3) - 2 == 0
  1420. /// let abs_difference = (x.cbrt() - 2.0).abs();
  1421. ///
  1422. /// assert!(abs_difference < 1e-10);
  1423. /// ```
  1424. fn cbrt(self) -> Self;
  1425. /// Calculate the length of the hypotenuse of a right-angle triangle given
  1426. /// legs of length `x` and `y`.
  1427. ///
  1428. /// ```
  1429. /// use num_traits::Float;
  1430. ///
  1431. /// let x = 2.0;
  1432. /// let y = 3.0;
  1433. ///
  1434. /// // sqrt(x^2 + y^2)
  1435. /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
  1436. ///
  1437. /// assert!(abs_difference < 1e-10);
  1438. /// ```
  1439. fn hypot(self, other: Self) -> Self;
  1440. /// Computes the sine of a number (in radians).
  1441. ///
  1442. /// ```
  1443. /// use num_traits::Float;
  1444. /// use std::f64;
  1445. ///
  1446. /// let x = f64::consts::PI/2.0;
  1447. ///
  1448. /// let abs_difference = (x.sin() - 1.0).abs();
  1449. ///
  1450. /// assert!(abs_difference < 1e-10);
  1451. /// ```
  1452. fn sin(self) -> Self;
  1453. /// Computes the cosine of a number (in radians).
  1454. ///
  1455. /// ```
  1456. /// use num_traits::Float;
  1457. /// use std::f64;
  1458. ///
  1459. /// let x = 2.0*f64::consts::PI;
  1460. ///
  1461. /// let abs_difference = (x.cos() - 1.0).abs();
  1462. ///
  1463. /// assert!(abs_difference < 1e-10);
  1464. /// ```
  1465. fn cos(self) -> Self;
  1466. /// Computes the tangent of a number (in radians).
  1467. ///
  1468. /// ```
  1469. /// use num_traits::Float;
  1470. /// use std::f64;
  1471. ///
  1472. /// let x = f64::consts::PI/4.0;
  1473. /// let abs_difference = (x.tan() - 1.0).abs();
  1474. ///
  1475. /// assert!(abs_difference < 1e-14);
  1476. /// ```
  1477. fn tan(self) -> Self;
  1478. /// Computes the arcsine of a number. Return value is in radians in
  1479. /// the range [-pi/2, pi/2] or NaN if the number is outside the range
  1480. /// [-1, 1].
  1481. ///
  1482. /// ```
  1483. /// use num_traits::Float;
  1484. /// use std::f64;
  1485. ///
  1486. /// let f = f64::consts::PI / 2.0;
  1487. ///
  1488. /// // asin(sin(pi/2))
  1489. /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs();
  1490. ///
  1491. /// assert!(abs_difference < 1e-10);
  1492. /// ```
  1493. fn asin(self) -> Self;
  1494. /// Computes the arccosine of a number. Return value is in radians in
  1495. /// the range [0, pi] or NaN if the number is outside the range
  1496. /// [-1, 1].
  1497. ///
  1498. /// ```
  1499. /// use num_traits::Float;
  1500. /// use std::f64;
  1501. ///
  1502. /// let f = f64::consts::PI / 4.0;
  1503. ///
  1504. /// // acos(cos(pi/4))
  1505. /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs();
  1506. ///
  1507. /// assert!(abs_difference < 1e-10);
  1508. /// ```
  1509. fn acos(self) -> Self;
  1510. /// Computes the arctangent of a number. Return value is in radians in the
  1511. /// range [-pi/2, pi/2];
  1512. ///
  1513. /// ```
  1514. /// use num_traits::Float;
  1515. ///
  1516. /// let f = 1.0;
  1517. ///
  1518. /// // atan(tan(1))
  1519. /// let abs_difference = (f.tan().atan() - 1.0).abs();
  1520. ///
  1521. /// assert!(abs_difference < 1e-10);
  1522. /// ```
  1523. fn atan(self) -> Self;
  1524. /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`).
  1525. ///
  1526. /// * `x = 0`, `y = 0`: `0`
  1527. /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
  1528. /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
  1529. /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
  1530. ///
  1531. /// ```
  1532. /// use num_traits::Float;
  1533. /// use std::f64;
  1534. ///
  1535. /// let pi = f64::consts::PI;
  1536. /// // All angles from horizontal right (+x)
  1537. /// // 45 deg counter-clockwise
  1538. /// let x1 = 3.0;
  1539. /// let y1 = -3.0;
  1540. ///
  1541. /// // 135 deg clockwise
  1542. /// let x2 = -3.0;
  1543. /// let y2 = 3.0;
  1544. ///
  1545. /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs();
  1546. /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs();
  1547. ///
  1548. /// assert!(abs_difference_1 < 1e-10);
  1549. /// assert!(abs_difference_2 < 1e-10);
  1550. /// ```
  1551. fn atan2(self, other: Self) -> Self;
  1552. /// Simultaneously computes the sine and cosine of the number, `x`. Returns
  1553. /// `(sin(x), cos(x))`.
  1554. ///
  1555. /// ```
  1556. /// use num_traits::Float;
  1557. /// use std::f64;
  1558. ///
  1559. /// let x = f64::consts::PI/4.0;
  1560. /// let f = x.sin_cos();
  1561. ///
  1562. /// let abs_difference_0 = (f.0 - x.sin()).abs();
  1563. /// let abs_difference_1 = (f.1 - x.cos()).abs();
  1564. ///
  1565. /// assert!(abs_difference_0 < 1e-10);
  1566. /// assert!(abs_difference_0 < 1e-10);
  1567. /// ```
  1568. fn sin_cos(self) -> (Self, Self);
  1569. /// Returns `e^(self) - 1` in a way that is accurate even if the
  1570. /// number is close to zero.
  1571. ///
  1572. /// ```
  1573. /// use num_traits::Float;
  1574. ///
  1575. /// let x = 7.0;
  1576. ///
  1577. /// // e^(ln(7)) - 1
  1578. /// let abs_difference = (x.ln().exp_m1() - 6.0).abs();
  1579. ///
  1580. /// assert!(abs_difference < 1e-10);
  1581. /// ```
  1582. fn exp_m1(self) -> Self;
  1583. /// Returns `ln(1+n)` (natural logarithm) more accurately than if
  1584. /// the operations were performed separately.
  1585. ///
  1586. /// ```
  1587. /// use num_traits::Float;
  1588. /// use std::f64;
  1589. ///
  1590. /// let x = f64::consts::E - 1.0;
  1591. ///
  1592. /// // ln(1 + (e - 1)) == ln(e) == 1
  1593. /// let abs_difference = (x.ln_1p() - 1.0).abs();
  1594. ///
  1595. /// assert!(abs_difference < 1e-10);
  1596. /// ```
  1597. fn ln_1p(self) -> Self;
  1598. /// Hyperbolic sine function.
  1599. ///
  1600. /// ```
  1601. /// use num_traits::Float;
  1602. /// use std::f64;
  1603. ///
  1604. /// let e = f64::consts::E;
  1605. /// let x = 1.0;
  1606. ///
  1607. /// let f = x.sinh();
  1608. /// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
  1609. /// let g = (e*e - 1.0)/(2.0*e);
  1610. /// let abs_difference = (f - g).abs();
  1611. ///
  1612. /// assert!(abs_difference < 1e-10);
  1613. /// ```
  1614. fn sinh(self) -> Self;
  1615. /// Hyperbolic cosine function.
  1616. ///
  1617. /// ```
  1618. /// use num_traits::Float;
  1619. /// use std::f64;
  1620. ///
  1621. /// let e = f64::consts::E;
  1622. /// let x = 1.0;
  1623. /// let f = x.cosh();
  1624. /// // Solving cosh() at 1 gives this result
  1625. /// let g = (e*e + 1.0)/(2.0*e);
  1626. /// let abs_difference = (f - g).abs();
  1627. ///
  1628. /// // Same result
  1629. /// assert!(abs_difference < 1.0e-10);
  1630. /// ```
  1631. fn cosh(self) -> Self;
  1632. /// Hyperbolic tangent function.
  1633. ///
  1634. /// ```
  1635. /// use num_traits::Float;
  1636. /// use std::f64;
  1637. ///
  1638. /// let e = f64::consts::E;
  1639. /// let x = 1.0;
  1640. ///
  1641. /// let f = x.tanh();
  1642. /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
  1643. /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2));
  1644. /// let abs_difference = (f - g).abs();
  1645. ///
  1646. /// assert!(abs_difference < 1.0e-10);
  1647. /// ```
  1648. fn tanh(self) -> Self;
  1649. /// Inverse hyperbolic sine function.
  1650. ///
  1651. /// ```
  1652. /// use num_traits::Float;
  1653. ///
  1654. /// let x = 1.0;
  1655. /// let f = x.sinh().asinh();
  1656. ///
  1657. /// let abs_difference = (f - x).abs();
  1658. ///
  1659. /// assert!(abs_difference < 1.0e-10);
  1660. /// ```
  1661. fn asinh(self) -> Self;
  1662. /// Inverse hyperbolic cosine function.
  1663. ///
  1664. /// ```
  1665. /// use num_traits::Float;
  1666. ///
  1667. /// let x = 1.0;
  1668. /// let f = x.cosh().acosh();
  1669. ///
  1670. /// let abs_difference = (f - x).abs();
  1671. ///
  1672. /// assert!(abs_difference < 1.0e-10);
  1673. /// ```
  1674. fn acosh(self) -> Self;
  1675. /// Inverse hyperbolic tangent function.
  1676. ///
  1677. /// ```
  1678. /// use num_traits::Float;
  1679. /// use std::f64;
  1680. ///
  1681. /// let e = f64::consts::E;
  1682. /// let f = e.tanh().atanh();
  1683. ///
  1684. /// let abs_difference = (f - e).abs();
  1685. ///
  1686. /// assert!(abs_difference < 1.0e-10);
  1687. /// ```
  1688. fn atanh(self) -> Self;
  1689. /// Returns the mantissa, base 2 exponent, and sign as integers, respectively.
  1690. /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`.
  1691. ///
  1692. /// ```
  1693. /// use num_traits::Float;
  1694. ///
  1695. /// let num = 2.0f32;
  1696. ///
  1697. /// // (8388608, -22, 1)
  1698. /// let (mantissa, exponent, sign) = Float::integer_decode(num);
  1699. /// let sign_f = sign as f32;
  1700. /// let mantissa_f = mantissa as f32;
  1701. /// let exponent_f = num.powf(exponent as f32);
  1702. ///
  1703. /// // 1 * 8388608 * 2^(-22) == 2
  1704. /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs();
  1705. ///
  1706. /// assert!(abs_difference < 1e-10);
  1707. /// ```
  1708. fn integer_decode(self) -> (u64, i16, i8);
  1709. }
  1710. #[cfg(feature = "std")]
  1711. macro_rules! float_impl_std {
  1712. ($T:ident $decode:ident) => {
  1713. impl Float for $T {
  1714. constant! {
  1715. nan() -> $T::NAN;
  1716. infinity() -> $T::INFINITY;
  1717. neg_infinity() -> $T::NEG_INFINITY;
  1718. neg_zero() -> -0.0;
  1719. min_value() -> $T::MIN;
  1720. min_positive_value() -> $T::MIN_POSITIVE;
  1721. epsilon() -> $T::EPSILON;
  1722. max_value() -> $T::MAX;
  1723. }
  1724. #[inline]
  1725. #[allow(deprecated)]
  1726. fn abs_sub(self, other: Self) -> Self {
  1727. <$T>::abs_sub(self, other)
  1728. }
  1729. #[inline]
  1730. fn integer_decode(self) -> (u64, i16, i8) {
  1731. $decode(self)
  1732. }
  1733. forward! {
  1734. Self::is_nan(self) -> bool;
  1735. Self::is_infinite(self) -> bool;
  1736. Self::is_finite(self) -> bool;
  1737. Self::is_normal(self) -> bool;
  1738. Self::classify(self) -> FpCategory;
  1739. Self::floor(self) -> Self;
  1740. Self::ceil(self) -> Self;
  1741. Self::round(self) -> Self;
  1742. Self::trunc(self) -> Self;
  1743. Self::fract(self) -> Self;
  1744. Self::abs(self) -> Self;
  1745. Self::signum(self) -> Self;
  1746. Self::is_sign_positive(self) -> bool;
  1747. Self::is_sign_negative(self) -> bool;
  1748. Self::mul_add(self, a: Self, b: Self) -> Self;
  1749. Self::recip(self) -> Self;
  1750. Self::powi(self, n: i32) -> Self;
  1751. Self::powf(self, n: Self) -> Self;
  1752. Self::sqrt(self) -> Self;
  1753. Self::exp(self) -> Self;
  1754. Self::exp2(self) -> Self;
  1755. Self::ln(self) -> Self;
  1756. Self::log(self, base: Self) -> Self;
  1757. Self::log2(self) -> Self;
  1758. Self::log10(self) -> Self;
  1759. Self::to_degrees(self) -> Self;
  1760. Self::to_radians(self) -> Self;
  1761. Self::max(self, other: Self) -> Self;
  1762. Self::min(self, other: Self) -> Self;
  1763. Self::cbrt(self) -> Self;
  1764. Self::hypot(self, other: Self) -> Self;
  1765. Self::sin(self) -> Self;
  1766. Self::cos(self) -> Self;
  1767. Self::tan(self) -> Self;
  1768. Self::asin(self) -> Self;
  1769. Self::acos(self) -> Self;
  1770. Self::atan(self) -> Self;
  1771. Self::atan2(self, other: Self) -> Self;
  1772. Self::sin_cos(self) -> (Self, Self);
  1773. Self::exp_m1(self) -> Self;
  1774. Self::ln_1p(self) -> Self;
  1775. Self::sinh(self) -> Self;
  1776. Self::cosh(self) -> Self;
  1777. Self::tanh(self) -> Self;
  1778. Self::asinh(self) -> Self;
  1779. Self::acosh(self) -> Self;
  1780. Self::atanh(self) -> Self;
  1781. }
  1782. }
  1783. };
  1784. }
  1785. #[cfg(all(not(feature = "std"), feature = "libm"))]
  1786. macro_rules! float_impl_libm {
  1787. ($T:ident $decode:ident) => {
  1788. constant! {
  1789. nan() -> $T::NAN;
  1790. infinity() -> $T::INFINITY;
  1791. neg_infinity() -> $T::NEG_INFINITY;
  1792. neg_zero() -> -0.0;
  1793. min_value() -> $T::MIN;
  1794. min_positive_value() -> $T::MIN_POSITIVE;
  1795. epsilon() -> $T::EPSILON;
  1796. max_value() -> $T::MAX;
  1797. }
  1798. #[inline]
  1799. fn integer_decode(self) -> (u64, i16, i8) {
  1800. $decode(self)
  1801. }
  1802. #[inline]
  1803. fn fract(self) -> Self {
  1804. self - FloatCore::trunc(self)
  1805. }
  1806. #[inline]
  1807. fn log(self, base: Self) -> Self {
  1808. self.ln() / base.ln()
  1809. }
  1810. forward! {
  1811. FloatCore::is_nan(self) -> bool;
  1812. FloatCore::is_infinite(self) -> bool;
  1813. FloatCore::is_finite(self) -> bool;
  1814. FloatCore::is_normal(self) -> bool;
  1815. FloatCore::classify(self) -> FpCategory;
  1816. FloatCore::signum(self) -> Self;
  1817. FloatCore::is_sign_positive(self) -> bool;
  1818. FloatCore::is_sign_negative(self) -> bool;
  1819. FloatCore::recip(self) -> Self;
  1820. FloatCore::powi(self, n: i32) -> Self;
  1821. FloatCore::to_degrees(self) -> Self;
  1822. FloatCore::to_radians(self) -> Self;
  1823. FloatCore::max(self, other: Self) -> Self;
  1824. FloatCore::min(self, other: Self) -> Self;
  1825. }
  1826. };
  1827. }
  1828. fn integer_decode_f32(f: f32) -> (u64, i16, i8) {
  1829. // Safety: this identical to the implementation of f32::to_bits(),
  1830. // which is only available starting at Rust 1.20
  1831. let bits: u32 = unsafe { mem::transmute(f) };
  1832. let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 };
  1833. let mut exponent: i16 = ((bits >> 23) & 0xff) as i16;
  1834. let mantissa = if exponent == 0 {
  1835. (bits & 0x7fffff) << 1
  1836. } else {
  1837. (bits & 0x7fffff) | 0x800000
  1838. };
  1839. // Exponent bias + mantissa shift
  1840. exponent -= 127 + 23;
  1841. (mantissa as u64, exponent, sign)
  1842. }
  1843. fn integer_decode_f64(f: f64) -> (u64, i16, i8) {
  1844. // Safety: this identical to the implementation of f64::to_bits(),
  1845. // which is only available starting at Rust 1.20
  1846. let bits: u64 = unsafe { mem::transmute(f) };
  1847. let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
  1848. let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
  1849. let mantissa = if exponent == 0 {
  1850. (bits & 0xfffffffffffff) << 1
  1851. } else {
  1852. (bits & 0xfffffffffffff) | 0x10000000000000
  1853. };
  1854. // Exponent bias + mantissa shift
  1855. exponent -= 1023 + 52;
  1856. (mantissa, exponent, sign)
  1857. }
  1858. #[cfg(feature = "std")]
  1859. float_impl_std!(f32 integer_decode_f32);
  1860. #[cfg(feature = "std")]
  1861. float_impl_std!(f64 integer_decode_f64);
  1862. #[cfg(all(not(feature = "std"), feature = "libm"))]
  1863. impl Float for f32 {
  1864. float_impl_libm!(f32 integer_decode_f32);
  1865. #[inline]
  1866. #[allow(deprecated)]
  1867. fn abs_sub(self, other: Self) -> Self {
  1868. libm::fdimf(self, other)
  1869. }
  1870. #[inline]
  1871. fn floor(self) -> Self {
  1872. libm::floorf(self)
  1873. }
  1874. #[inline]
  1875. fn ceil(self) -> Self {
  1876. libm::ceilf(self)
  1877. }
  1878. #[inline]
  1879. fn round(self) -> Self {
  1880. libm::roundf(self)
  1881. }
  1882. #[inline]
  1883. fn trunc(self) -> Self {
  1884. libm::truncf(self)
  1885. }
  1886. #[inline]
  1887. fn abs(self) -> Self {
  1888. libm::fabsf(self)
  1889. }
  1890. #[inline]
  1891. fn mul_add(self, a: Self, b: Self) -> Self {
  1892. libm::fmaf(self, a, b)
  1893. }
  1894. #[inline]
  1895. fn powf(self, n: Self) -> Self {
  1896. libm::powf(self, n)
  1897. }
  1898. #[inline]
  1899. fn sqrt(self) -> Self {
  1900. libm::sqrtf(self)
  1901. }
  1902. #[inline]
  1903. fn exp(self) -> Self {
  1904. libm::expf(self)
  1905. }
  1906. #[inline]
  1907. fn exp2(self) -> Self {
  1908. libm::exp2f(self)
  1909. }
  1910. #[inline]
  1911. fn ln(self) -> Self {
  1912. libm::logf(self)
  1913. }
  1914. #[inline]
  1915. fn log2(self) -> Self {
  1916. libm::log2f(self)
  1917. }
  1918. #[inline]
  1919. fn log10(self) -> Self {
  1920. libm::log10f(self)
  1921. }
  1922. #[inline]
  1923. fn cbrt(self) -> Self {
  1924. libm::cbrtf(self)
  1925. }
  1926. #[inline]
  1927. fn hypot(self, other: Self) -> Self {
  1928. libm::hypotf(self, other)
  1929. }
  1930. #[inline]
  1931. fn sin(self) -> Self {
  1932. libm::sinf(self)
  1933. }
  1934. #[inline]
  1935. fn cos(self) -> Self {
  1936. libm::cosf(self)
  1937. }
  1938. #[inline]
  1939. fn tan(self) -> Self {
  1940. libm::tanf(self)
  1941. }
  1942. #[inline]
  1943. fn asin(self) -> Self {
  1944. libm::asinf(self)
  1945. }
  1946. #[inline]
  1947. fn acos(self) -> Self {
  1948. libm::acosf(self)
  1949. }
  1950. #[inline]
  1951. fn atan(self) -> Self {
  1952. libm::atanf(self)
  1953. }
  1954. #[inline]
  1955. fn atan2(self, other: Self) -> Self {
  1956. libm::atan2f(self, other)
  1957. }
  1958. #[inline]
  1959. fn sin_cos(self) -> (Self, Self) {
  1960. libm::sincosf(self)
  1961. }
  1962. #[inline]
  1963. fn exp_m1(self) -> Self {
  1964. libm::expm1f(self)
  1965. }
  1966. #[inline]
  1967. fn ln_1p(self) -> Self {
  1968. libm::log1pf(self)
  1969. }
  1970. #[inline]
  1971. fn sinh(self) -> Self {
  1972. libm::sinhf(self)
  1973. }
  1974. #[inline]
  1975. fn cosh(self) -> Self {
  1976. libm::coshf(self)
  1977. }
  1978. #[inline]
  1979. fn tanh(self) -> Self {
  1980. libm::tanhf(self)
  1981. }
  1982. #[inline]
  1983. fn asinh(self) -> Self {
  1984. libm::asinhf(self)
  1985. }
  1986. #[inline]
  1987. fn acosh(self) -> Self {
  1988. libm::acoshf(self)
  1989. }
  1990. #[inline]
  1991. fn atanh(self) -> Self {
  1992. libm::atanhf(self)
  1993. }
  1994. }
  1995. #[cfg(all(not(feature = "std"), feature = "libm"))]
  1996. impl Float for f64 {
  1997. float_impl_libm!(f64 integer_decode_f64);
  1998. #[inline]
  1999. #[allow(deprecated)]
  2000. fn abs_sub(self, other: Self) -> Self {
  2001. libm::fdim(self, other)
  2002. }
  2003. #[inline]
  2004. fn floor(self) -> Self {
  2005. libm::floor(self)
  2006. }
  2007. #[inline]
  2008. fn ceil(self) -> Self {
  2009. libm::ceil(self)
  2010. }
  2011. #[inline]
  2012. fn round(self) -> Self {
  2013. libm::round(self)
  2014. }
  2015. #[inline]
  2016. fn trunc(self) -> Self {
  2017. libm::trunc(self)
  2018. }
  2019. #[inline]
  2020. fn abs(self) -> Self {
  2021. libm::fabs(self)
  2022. }
  2023. #[inline]
  2024. fn mul_add(self, a: Self, b: Self) -> Self {
  2025. libm::fma(self, a, b)
  2026. }
  2027. #[inline]
  2028. fn powf(self, n: Self) -> Self {
  2029. libm::pow(self, n)
  2030. }
  2031. #[inline]
  2032. fn sqrt(self) -> Self {
  2033. libm::sqrt(self)
  2034. }
  2035. #[inline]
  2036. fn exp(self) -> Self {
  2037. libm::exp(self)
  2038. }
  2039. #[inline]
  2040. fn exp2(self) -> Self {
  2041. libm::exp2(self)
  2042. }
  2043. #[inline]
  2044. fn ln(self) -> Self {
  2045. libm::log(self)
  2046. }
  2047. #[inline]
  2048. fn log2(self) -> Self {
  2049. libm::log2(self)
  2050. }
  2051. #[inline]
  2052. fn log10(self) -> Self {
  2053. libm::log10(self)
  2054. }
  2055. #[inline]
  2056. fn cbrt(self) -> Self {
  2057. libm::cbrt(self)
  2058. }
  2059. #[inline]
  2060. fn hypot(self, other: Self) -> Self {
  2061. libm::hypot(self, other)
  2062. }
  2063. #[inline]
  2064. fn sin(self) -> Self {
  2065. libm::sin(self)
  2066. }
  2067. #[inline]
  2068. fn cos(self) -> Self {
  2069. libm::cos(self)
  2070. }
  2071. #[inline]
  2072. fn tan(self) -> Self {
  2073. libm::tan(self)
  2074. }
  2075. #[inline]
  2076. fn asin(self) -> Self {
  2077. libm::asin(self)
  2078. }
  2079. #[inline]
  2080. fn acos(self) -> Self {
  2081. libm::acos(self)
  2082. }
  2083. #[inline]
  2084. fn atan(self) -> Self {
  2085. libm::atan(self)
  2086. }
  2087. #[inline]
  2088. fn atan2(self, other: Self) -> Self {
  2089. libm::atan2(self, other)
  2090. }
  2091. #[inline]
  2092. fn sin_cos(self) -> (Self, Self) {
  2093. libm::sincos(self)
  2094. }
  2095. #[inline]
  2096. fn exp_m1(self) -> Self {
  2097. libm::expm1(self)
  2098. }
  2099. #[inline]
  2100. fn ln_1p(self) -> Self {
  2101. libm::log1p(self)
  2102. }
  2103. #[inline]
  2104. fn sinh(self) -> Self {
  2105. libm::sinh(self)
  2106. }
  2107. #[inline]
  2108. fn cosh(self) -> Self {
  2109. libm::cosh(self)
  2110. }
  2111. #[inline]
  2112. fn tanh(self) -> Self {
  2113. libm::tanh(self)
  2114. }
  2115. #[inline]
  2116. fn asinh(self) -> Self {
  2117. libm::asinh(self)
  2118. }
  2119. #[inline]
  2120. fn acosh(self) -> Self {
  2121. libm::acosh(self)
  2122. }
  2123. #[inline]
  2124. fn atanh(self) -> Self {
  2125. libm::atanh(self)
  2126. }
  2127. }
  2128. macro_rules! float_const_impl {
  2129. ($(#[$doc:meta] $constant:ident,)+) => (
  2130. #[allow(non_snake_case)]
  2131. pub trait FloatConst {
  2132. $(#[$doc] fn $constant() -> Self;)+
  2133. #[doc = "Return the full circle constant `τ`."]
  2134. #[inline]
  2135. fn TAU() -> Self where Self: Sized + Add<Self, Output = Self> {
  2136. Self::PI() + Self::PI()
  2137. }
  2138. #[doc = "Return `log10(2.0)`."]
  2139. #[inline]
  2140. fn LOG10_2() -> Self where Self: Sized + Div<Self, Output = Self> {
  2141. Self::LN_2() / Self::LN_10()
  2142. }
  2143. #[doc = "Return `log2(10.0)`."]
  2144. #[inline]
  2145. fn LOG2_10() -> Self where Self: Sized + Div<Self, Output = Self> {
  2146. Self::LN_10() / Self::LN_2()
  2147. }
  2148. }
  2149. float_const_impl! { @float f32, $($constant,)+ }
  2150. float_const_impl! { @float f64, $($constant,)+ }
  2151. );
  2152. (@float $T:ident, $($constant:ident,)+) => (
  2153. impl FloatConst for $T {
  2154. constant! {
  2155. $( $constant() -> $T::consts::$constant; )+
  2156. TAU() -> 6.28318530717958647692528676655900577;
  2157. LOG10_2() -> 0.301029995663981195213738894724493027;
  2158. LOG2_10() -> 3.32192809488736234787031942948939018;
  2159. }
  2160. }
  2161. );
  2162. }
  2163. float_const_impl! {
  2164. #[doc = "Return Euler’s number."]
  2165. E,
  2166. #[doc = "Return `1.0 / π`."]
  2167. FRAC_1_PI,
  2168. #[doc = "Return `1.0 / sqrt(2.0)`."]
  2169. FRAC_1_SQRT_2,
  2170. #[doc = "Return `2.0 / π`."]
  2171. FRAC_2_PI,
  2172. #[doc = "Return `2.0 / sqrt(π)`."]
  2173. FRAC_2_SQRT_PI,
  2174. #[doc = "Return `π / 2.0`."]
  2175. FRAC_PI_2,
  2176. #[doc = "Return `π / 3.0`."]
  2177. FRAC_PI_3,
  2178. #[doc = "Return `π / 4.0`."]
  2179. FRAC_PI_4,
  2180. #[doc = "Return `π / 6.0`."]
  2181. FRAC_PI_6,
  2182. #[doc = "Return `π / 8.0`."]
  2183. FRAC_PI_8,
  2184. #[doc = "Return `ln(10.0)`."]
  2185. LN_10,
  2186. #[doc = "Return `ln(2.0)`."]
  2187. LN_2,
  2188. #[doc = "Return `log10(e)`."]
  2189. LOG10_E,
  2190. #[doc = "Return `log2(e)`."]
  2191. LOG2_E,
  2192. #[doc = "Return Archimedes’ constant `π`."]
  2193. PI,
  2194. #[doc = "Return `sqrt(2.0)`."]
  2195. SQRT_2,
  2196. }
  2197. #[cfg(test)]
  2198. mod tests {
  2199. use core::f64::consts;
  2200. const DEG_RAD_PAIRS: [(f64, f64); 7] = [
  2201. (0.0, 0.),
  2202. (22.5, consts::FRAC_PI_8),
  2203. (30.0, consts::FRAC_PI_6),
  2204. (45.0, consts::FRAC_PI_4),
  2205. (60.0, consts::FRAC_PI_3),
  2206. (90.0, consts::FRAC_PI_2),
  2207. (180.0, consts::PI),
  2208. ];
  2209. #[test]
  2210. fn convert_deg_rad() {
  2211. use float::FloatCore;
  2212. for &(deg, rad) in &DEG_RAD_PAIRS {
  2213. assert!((FloatCore::to_degrees(rad) - deg).abs() < 1e-6);
  2214. assert!((FloatCore::to_radians(deg) - rad).abs() < 1e-6);
  2215. let (deg, rad) = (deg as f32, rad as f32);
  2216. assert!((FloatCore::to_degrees(rad) - deg).abs() < 1e-5);
  2217. assert!((FloatCore::to_radians(deg) - rad).abs() < 1e-5);
  2218. }
  2219. }
  2220. #[cfg(any(feature = "std", feature = "libm"))]
  2221. #[test]
  2222. fn convert_deg_rad_std() {
  2223. for &(deg, rad) in &DEG_RAD_PAIRS {
  2224. use Float;
  2225. assert!((Float::to_degrees(rad) - deg).abs() < 1e-6);
  2226. assert!((Float::to_radians(deg) - rad).abs() < 1e-6);
  2227. let (deg, rad) = (deg as f32, rad as f32);
  2228. assert!((Float::to_degrees(rad) - deg).abs() < 1e-5);
  2229. assert!((Float::to_radians(deg) - rad).abs() < 1e-5);
  2230. }
  2231. }
  2232. #[test]
  2233. // This fails with the forwarded `std` implementation in Rust 1.8.
  2234. // To avoid the failure, the test is limited to `no_std` builds.
  2235. #[cfg(not(feature = "std"))]
  2236. fn to_degrees_rounding() {
  2237. use float::FloatCore;
  2238. assert_eq!(
  2239. FloatCore::to_degrees(1_f32),
  2240. 57.2957795130823208767981548141051703
  2241. );
  2242. }
  2243. #[test]
  2244. #[cfg(any(feature = "std", feature = "libm"))]
  2245. fn extra_logs() {
  2246. use float::{Float, FloatConst};
  2247. fn check<F: Float + FloatConst>(diff: F) {
  2248. let _2 = F::from(2.0).unwrap();
  2249. assert!((F::LOG10_2() - F::log10(_2)).abs() < diff);
  2250. assert!((F::LOG10_2() - F::LN_2() / F::LN_10()).abs() < diff);
  2251. let _10 = F::from(10.0).unwrap();
  2252. assert!((F::LOG2_10() - F::log2(_10)).abs() < diff);
  2253. assert!((F::LOG2_10() - F::LN_10() / F::LN_2()).abs() < diff);
  2254. }
  2255. check::<f32>(1e-6);
  2256. check::<f64>(1e-12);
  2257. }
  2258. }