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