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