num_traits/
float.rs

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