num_primitive/
float.rs

1use crate::{PrimitiveNumber, PrimitiveNumberRef, PrimitiveUnsigned};
2
3use core::cmp::Ordering;
4use core::f32::consts as f32_consts;
5use core::f64::consts as f64_consts;
6use core::num::{FpCategory, ParseFloatError};
7
8struct SealedToken;
9
10/// Trait for all primitive [floating-point types], including the supertrait [`PrimitiveNumber`].
11///
12/// This encapsulates trait implementations, constants, and inherent methods that are common among
13/// the primitive floating-point types, [`f32`] and [`f64`]. Unstable types [`f16`] and [`f128`]
14/// will be added once they are stabilized.
15///
16/// See the corresponding items on the individual types for more documentation and examples.
17///
18/// This trait is sealed with a private trait to prevent downstream implementations, so we may
19/// continue to expand along with the standard library without worrying about breaking changes for
20/// implementors.
21///
22/// [floating-point types]: https://doc.rust-lang.org/reference/types/numeric.html#r-type.numeric.float
23///
24/// # Examples
25///
26/// This example requires the `std` feature for [`powi`][Self::powi] and [`sqrt`][Self::sqrt]:
27///
28#[cfg_attr(feature = "std", doc = "```")]
29#[cfg_attr(not(feature = "std"), doc = "```ignore")]
30/// use num_primitive::PrimitiveFloat;
31///
32/// // Euclidean distance, √(∑(aᵢ - bᵢ)²)
33/// fn distance<T: PrimitiveFloat>(a: &[T], b: &[T]) -> T {
34///     assert_eq!(a.len(), b.len());
35///     core::iter::zip(a, b).map(|(a, b)| (*a - b).powi(2)).sum::<T>().sqrt()
36/// }
37///
38/// assert_eq!(distance::<f32>(&[0., 0.], &[3., 4.]), 5.);
39/// assert_eq!(distance::<f64>(&[0., 1., 2.], &[1., 3., 0.]), 3.);
40/// ```
41///
42/// This example works without any features:
43///
44/// ```
45/// use num_primitive::PrimitiveFloat;
46///
47/// // Squared Euclidean distance, ∑(aᵢ - bᵢ)²
48/// fn distance_squared<T: PrimitiveFloat>(a: &[T], b: &[T]) -> T {
49///     assert_eq!(a.len(), b.len());
50///     core::iter::zip(a, b).map(|(a, b)| (*a - b)).map(|x| x * x).sum::<T>()
51/// }
52///
53/// assert_eq!(distance_squared::<f32>(&[0., 0.], &[3., 4.]), 25.);
54/// assert_eq!(distance_squared::<f64>(&[0., 1., 2.], &[1., 3., 0.]), 9.);
55/// ```
56pub trait PrimitiveFloat:
57    PrimitiveNumber
58    + PrimitiveFloatToInt<i8>
59    + PrimitiveFloatToInt<i16>
60    + PrimitiveFloatToInt<i32>
61    + PrimitiveFloatToInt<i64>
62    + PrimitiveFloatToInt<i128>
63    + PrimitiveFloatToInt<isize>
64    + PrimitiveFloatToInt<u8>
65    + PrimitiveFloatToInt<u16>
66    + PrimitiveFloatToInt<u32>
67    + PrimitiveFloatToInt<u64>
68    + PrimitiveFloatToInt<u128>
69    + PrimitiveFloatToInt<usize>
70    + core::convert::From<i8>
71    + core::convert::From<u8>
72    + core::ops::Neg<Output = Self>
73    + core::str::FromStr<Err = ParseFloatError>
74{
75    /// Approximate number of significant digits in base 10.
76    const DIGITS: u32;
77
78    /// Machine epsilon value.
79    const EPSILON: Self;
80
81    /// Infinity (∞).
82    const INFINITY: Self;
83
84    /// Number of significant digits in base 2.
85    const MANTISSA_DIGITS: u32;
86
87    /// Largest finite value.
88    const MAX: Self;
89
90    /// Maximum _x_ for which 10<sup>_x_</sup> is normal.
91    const MAX_10_EXP: i32;
92
93    /// Maximum possible power of 2 exponent.
94    const MAX_EXP: i32;
95
96    /// Smallest finite value.
97    const MIN: Self;
98
99    /// Minimum _x_ for which 10<sup>_x_</sup> is normal.
100    const MIN_10_EXP: i32;
101
102    /// One greater than the minimum possible normal power of 2 exponent.
103    const MIN_EXP: i32;
104
105    /// Smallest positive normal value.
106    const MIN_POSITIVE: Self;
107
108    /// Not a Number (NaN).
109    const NAN: Self;
110
111    /// Negative infinity (−∞).
112    const NEG_INFINITY: Self;
113
114    /// The radix or base of the internal representation.
115    const RADIX: u32;
116
117    // The following are not inherent consts, rather from `core::{float}::consts`.
118
119    /// Euler's number (e)
120    const E: Self;
121
122    /// 1/π
123    const FRAC_1_PI: Self;
124
125    /// 1/sqrt(2)
126    const FRAC_1_SQRT_2: Self;
127
128    /// 2/π
129    const FRAC_2_PI: Self;
130
131    /// 2/sqrt(π)
132    const FRAC_2_SQRT_PI: Self;
133
134    /// π/2
135    const FRAC_PI_2: Self;
136
137    /// π/3
138    const FRAC_PI_3: Self;
139
140    /// π/4
141    const FRAC_PI_4: Self;
142
143    /// π/6
144    const FRAC_PI_6: Self;
145
146    /// π/8
147    const FRAC_PI_8: Self;
148
149    /// ln(2)
150    const LN_2: Self;
151
152    /// ln(10)
153    const LN_10: Self;
154
155    /// log₂(10)
156    const LOG2_10: Self;
157
158    /// log₂(e)
159    const LOG2_E: Self;
160
161    /// log₁₀(2)
162    const LOG10_2: Self;
163
164    /// log₁₀(e)
165    const LOG10_E: Self;
166
167    /// Archimedes' constant (π)
168    const PI: Self;
169
170    /// sqrt(2)
171    const SQRT_2: Self;
172
173    /// The full circle constant (τ)
174    const TAU: Self;
175
176    /// An unsigned integer type used by methods [`from_bits`][Self::from_bits] and
177    /// [`to_bits`][Self::to_bits].
178    type Bits: PrimitiveUnsigned;
179
180    /// Computes the absolute value of `self`.
181    fn abs(self) -> Self;
182
183    /// Restrict a value to a certain interval unless it is NaN.
184    fn clamp(self, min: Self, max: Self) -> Self;
185
186    /// Returns the floating point category of the number. If only one property is going to be
187    /// tested, it is generally faster to use the specific predicate instead.
188    fn classify(self) -> FpCategory;
189
190    /// Returns a number composed of the magnitude of `self` and the sign of sign.
191    fn copysign(self, sign: Self) -> Self;
192
193    /// Raw transmutation from `Self::Bits`.
194    fn from_bits(value: Self::Bits) -> Self;
195
196    /// Returns `true` if this number is neither infinite nor NaN.
197    fn is_finite(self) -> bool;
198
199    /// Returns `true` if this value is positive infinity or negative infinity.
200    fn is_infinite(self) -> bool;
201
202    /// Returns `true` if this value is NaN.
203    fn is_nan(self) -> bool;
204
205    /// Returns `true` if the number is neither zero, infinite, subnormal, or NaN.
206    fn is_normal(self) -> bool;
207
208    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with negative sign bit
209    /// and negative infinity.
210    fn is_sign_negative(self) -> bool;
211
212    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with positive sign bit
213    /// and positive infinity.
214    fn is_sign_positive(self) -> bool;
215
216    /// Returns `true` if the number is subnormal.
217    fn is_subnormal(self) -> bool;
218
219    /// Returns the maximum of the two numbers, ignoring NaN.
220    fn max(self, other: Self) -> Self;
221
222    /// Returns the minimum of the two numbers, ignoring NaN.
223    fn min(self, other: Self) -> Self;
224
225    /// Returns the greatest number less than `self`.
226    fn next_down(self) -> Self;
227
228    /// Returns the least number greater than `self`.
229    fn next_up(self) -> Self;
230
231    /// Takes the reciprocal (inverse) of a number, `1/x`.
232    fn recip(self) -> Self;
233
234    /// Returns a number that represents the sign of `self`.
235    fn signum(self) -> Self;
236
237    /// Raw transmutation to `Self::Bits`.
238    fn to_bits(self) -> Self::Bits;
239
240    /// Converts radians to degrees.
241    fn to_degrees(self) -> Self;
242
243    /// Converts degrees to radians.
244    fn to_radians(self) -> Self;
245
246    /// Returns the ordering between `self` and `other`.
247    fn total_cmp(&self, other: &Self) -> Ordering;
248
249    /// Rounds toward zero and converts to any primitive integer type, assuming that the value is
250    /// finite and fits in that type.
251    ///
252    /// # Safety
253    ///
254    /// The value must:
255    ///
256    /// * Not be `NaN`
257    /// * Not be infinite
258    /// * Be representable in the return type `Int`, after truncating off its fractional part
259    unsafe fn to_int_unchecked<Int>(self) -> Int
260    where
261        Self: PrimitiveFloatToInt<Int>;
262
263    /// Computes the arccosine of a number. Return value is in radians in the range [0, pi] or NaN
264    /// if the number is outside the range [-1, 1].
265    #[cfg(feature = "std")]
266    fn acos(self) -> Self;
267
268    /// Inverse hyperbolic cosine function.
269    #[cfg(feature = "std")]
270    fn acosh(self) -> Self;
271
272    /// Computes the arcsine of a number. Return value is in radians in the range [-pi/2, pi/2] or
273    /// NaN if the number is outside the range [-1, 1].
274    #[cfg(feature = "std")]
275    fn asin(self) -> Self;
276
277    /// Inverse hyperbolic sine function.
278    #[cfg(feature = "std")]
279    fn asinh(self) -> Self;
280
281    /// Computes the arctangent of a number. Return value is in radians in the range [-pi/2, pi/2];
282    #[cfg(feature = "std")]
283    fn atan(self) -> Self;
284
285    /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.
286    #[cfg(feature = "std")]
287    fn atan2(self, other: Self) -> Self;
288
289    /// Inverse hyperbolic tangent function.
290    #[cfg(feature = "std")]
291    fn atanh(self) -> Self;
292
293    /// Returns the cube root of a number.
294    #[cfg(feature = "std")]
295    fn cbrt(self) -> Self;
296
297    /// Returns the smallest integer greater than or equal to `self`.
298    #[cfg(feature = "std")]
299    fn ceil(self) -> Self;
300
301    /// Computes the cosine of a number (in radians).
302    #[cfg(feature = "std")]
303    fn cos(self) -> Self;
304
305    /// Hyperbolic cosine function.
306    #[cfg(feature = "std")]
307    fn cosh(self) -> Self;
308
309    /// Calculates Euclidean division, the matching method for `rem_euclid`.
310    #[cfg(feature = "std")]
311    fn div_euclid(self, rhs: Self) -> Self;
312
313    /// Returns `e^(self)`, (the exponential function).
314    #[cfg(feature = "std")]
315    fn exp(self) -> Self;
316
317    /// Returns `2^(self)`.
318    #[cfg(feature = "std")]
319    fn exp2(self) -> Self;
320
321    /// Returns `e^(self) - 1` in a way that is accurate even if the number is close to zero.
322    #[cfg(feature = "std")]
323    fn exp_m1(self) -> Self;
324
325    /// Returns the largest integer less than or equal to `self`.
326    #[cfg(feature = "std")]
327    fn floor(self) -> Self;
328
329    /// Returns the fractional part of `self`.
330    #[cfg(feature = "std")]
331    fn fract(self) -> Self;
332
333    /// Compute the distance between the origin and a point (`x`, `y`) on the Euclidean plane.
334    /// Equivalently, compute the length of the hypotenuse of a right-angle triangle with other
335    /// sides having length `x.abs()` and `y.abs()`.
336    #[cfg(feature = "std")]
337    fn hypot(self, other: Self) -> Self;
338
339    /// Returns the natural logarithm of the number.
340    #[cfg(feature = "std")]
341    fn ln(self) -> Self;
342
343    /// Returns `ln(1+n)` (natural logarithm) more accurately than if the operations were performed
344    /// separately.
345    #[cfg(feature = "std")]
346    fn ln_1p(self) -> Self;
347
348    /// Returns the logarithm of the number with respect to an arbitrary base.
349    #[cfg(feature = "std")]
350    fn log(self, base: Self) -> Self;
351
352    /// Returns the base 2 logarithm of the number.
353    #[cfg(feature = "std")]
354    fn log2(self) -> Self;
355
356    /// Returns the base 10 logarithm of the number.
357    #[cfg(feature = "std")]
358    fn log10(self) -> Self;
359
360    /// Fused multiply-add. Computes `(self * a) + b` with only one rounding error, yielding a more
361    /// accurate result than an unfused multiply-add.
362    #[cfg(feature = "std")]
363    fn mul_add(self, a: Self, b: Self) -> Self;
364
365    /// Raises a number to a floating point power.
366    #[cfg(feature = "std")]
367    fn powf(self, n: Self) -> Self;
368
369    /// Raises a number to an integer power.
370    #[cfg(feature = "std")]
371    fn powi(self, n: i32) -> Self;
372
373    /// Calculates the least nonnegative remainder of `self (mod rhs)`.
374    #[cfg(feature = "std")]
375    fn rem_euclid(self, rhs: Self) -> Self;
376
377    /// Returns the nearest integer to `self`. If a value is half-way between two integers, round
378    /// away from `0.0`.
379    #[cfg(feature = "std")]
380    fn round(self) -> Self;
381
382    /// Returns the nearest integer to a number. Rounds half-way cases to the number with an even
383    /// least significant digit.
384    #[cfg(feature = "std")]
385    fn round_ties_even(self) -> Self;
386
387    /// Computes the sine of a number (in radians).
388    #[cfg(feature = "std")]
389    fn sin(self) -> Self;
390
391    /// Simultaneously computes the sine and cosine of the number, `x`. Returns `(sin(x), cos(x))`.
392    #[cfg(feature = "std")]
393    fn sin_cos(self) -> (Self, Self);
394
395    /// Hyperbolic sine function.
396    #[cfg(feature = "std")]
397    fn sinh(self) -> Self;
398
399    /// Returns the square root of a number.
400    #[cfg(feature = "std")]
401    fn sqrt(self) -> Self;
402
403    /// Computes the tangent of a number (in radians).
404    #[cfg(feature = "std")]
405    fn tan(self) -> Self;
406
407    /// Hyperbolic tangent function.
408    #[cfg(feature = "std")]
409    fn tanh(self) -> Self;
410
411    /// Returns the integer part of `self`. This means that non-integer numbers are always
412    /// truncated towards zero.
413    #[cfg(feature = "std")]
414    fn trunc(self) -> Self;
415}
416
417/// Trait for references to primitive floating-point types ([`PrimitiveFloat`]).
418///
419/// This enables traits like the standard operators in generic code,
420/// e.g. `where &T: PrimitiveFloatRef<T>`.
421pub trait PrimitiveFloatRef<T>: PrimitiveNumberRef<T> + core::ops::Neg<Output = T> {}
422
423/// Trait for conversions supported by [`PrimitiveFloat::to_int_unchecked`].
424///
425/// This is effectively the same as the unstable [`core::convert::FloatToInt`], implemented for all
426/// combinations of [`PrimitiveFloat`] and [`PrimitiveInteger`][crate::PrimitiveInteger].
427///
428/// # Examples
429///
430/// `PrimitiveFloatToInt<{integer}>` is a supertrait of [`PrimitiveFloat`] for all primitive
431/// integers, so you do not need to use this trait directly with concrete integer types.
432///
433/// ```
434/// use num_primitive::PrimitiveFloat;
435///
436/// fn pi<Float: PrimitiveFloat>() -> i32 {
437///     // SAFETY: π is finite, and truncated to 3 fits any int
438///     unsafe { Float::PI.to_int_unchecked() }
439/// }
440///
441/// assert_eq!(pi::<f32>(), 3i32);
442/// assert_eq!(pi::<f64>(), 3i32);
443/// ```
444///
445/// However, if the integer type is also generic, an explicit type constraint is needed.
446///
447/// ```
448/// use num_primitive::{PrimitiveFloat, PrimitiveFloatToInt};
449///
450/// fn tau<Float, Int>() -> Int
451/// where
452///     Float: PrimitiveFloat + PrimitiveFloatToInt<Int>,
453/// {
454///     // SAFETY: τ is finite, and truncated to 6 fits any int
455///     unsafe { Float::TAU.to_int_unchecked() }
456/// }
457///
458/// assert_eq!(tau::<f32, i64>(), 6i64);
459/// assert_eq!(tau::<f64, u8>(), 6u8);
460/// ```
461///
462pub trait PrimitiveFloatToInt<Int> {
463    #[doc(hidden)]
464    #[expect(private_interfaces)]
465    unsafe fn __to_int_unchecked(x: Self, _: SealedToken) -> Int;
466}
467
468macro_rules! impl_float {
469    ($Float:ident, $consts:ident, $Bits:ty) => {
470        impl PrimitiveFloat for $Float {
471            use_consts!(Self::{
472                DIGITS: u32,
473                EPSILON: Self,
474                INFINITY: Self,
475                MANTISSA_DIGITS: u32,
476                MAX: Self,
477                MAX_10_EXP: i32,
478                MAX_EXP: i32,
479                MIN: Self,
480                MIN_10_EXP: i32,
481                MIN_EXP: i32,
482                MIN_POSITIVE: Self,
483                NAN: Self,
484                NEG_INFINITY: Self,
485                RADIX: u32,
486            });
487
488            use_consts!($consts::{
489                E: Self,
490                FRAC_1_PI: Self,
491                FRAC_1_SQRT_2: Self,
492                FRAC_2_PI: Self,
493                FRAC_2_SQRT_PI: Self,
494                FRAC_PI_2: Self,
495                FRAC_PI_3: Self,
496                FRAC_PI_4: Self,
497                FRAC_PI_6: Self,
498                FRAC_PI_8: Self,
499                LN_2: Self,
500                LN_10: Self,
501                LOG2_10: Self,
502                LOG2_E: Self,
503                LOG10_2: Self,
504                LOG10_E: Self,
505                PI: Self,
506                SQRT_2: Self,
507                TAU: Self,
508            });
509
510            type Bits = $Bits;
511
512            forward! {
513                fn from_bits(value: Self::Bits) -> Self;
514            }
515            forward! {
516                fn abs(self) -> Self;
517                fn clamp(self, min: Self, max: Self) -> Self;
518                fn classify(self) -> FpCategory;
519                fn copysign(self, sign: Self) -> Self;
520                fn is_finite(self) -> bool;
521                fn is_infinite(self) -> bool;
522                fn is_nan(self) -> bool;
523                fn is_normal(self) -> bool;
524                fn is_sign_negative(self) -> bool;
525                fn is_sign_positive(self) -> bool;
526                fn is_subnormal(self) -> bool;
527                fn max(self, other: Self) -> Self;
528                fn min(self, other: Self) -> Self;
529                fn next_down(self) -> Self;
530                fn next_up(self) -> Self;
531                fn recip(self) -> Self;
532                fn signum(self) -> Self;
533                fn to_bits(self) -> Self::Bits;
534                fn to_degrees(self) -> Self;
535                fn to_radians(self) -> Self;
536            }
537            forward! {
538                fn total_cmp(&self, other: &Self) -> Ordering;
539            }
540
541            // NOTE: This is still effectively forwarding, but we need some indirection
542            // to avoid naming the unstable `core::convert::FloatToInt`.
543            #[doc = forward_doc!(to_int_unchecked)]
544            #[inline]
545            unsafe fn to_int_unchecked<Int>(self) -> Int
546            where
547                Self: PrimitiveFloatToInt<Int>,
548            {
549                // SAFETY: we're just passing through here!
550                unsafe { <Self as PrimitiveFloatToInt<Int>>::__to_int_unchecked(self, SealedToken) }
551            }
552
553            // --- std-only methods ---
554
555            #[cfg(feature = "std")]
556            forward! {
557                fn acos(self) -> Self;
558                fn acosh(self) -> Self;
559                fn asin(self) -> Self;
560                fn asinh(self) -> Self;
561                fn atan(self) -> Self;
562                fn atan2(self, other: Self) -> Self;
563                fn atanh(self) -> Self;
564                fn cbrt(self) -> Self;
565                fn ceil(self) -> Self;
566                fn cos(self) -> Self;
567                fn cosh(self) -> Self;
568                fn div_euclid(self, rhs: Self) -> Self;
569                fn exp(self) -> Self;
570                fn exp2(self) -> Self;
571                fn exp_m1(self) -> Self;
572                fn floor(self) -> Self;
573                fn fract(self) -> Self;
574                fn hypot(self, other: Self) -> Self;
575                fn ln(self) -> Self;
576                fn ln_1p(self) -> Self;
577                fn log(self, base: Self) -> Self;
578                fn log2(self) -> Self;
579                fn log10(self) -> Self;
580                fn mul_add(self, a: Self, b: Self) -> Self;
581                fn powf(self, n: Self) -> Self;
582                fn powi(self, n: i32) -> Self;
583                fn rem_euclid(self, rhs: Self) -> Self;
584                fn round(self) -> Self;
585                fn round_ties_even(self) -> Self;
586                fn sin(self) -> Self;
587                fn sin_cos(self) -> (Self, Self);
588                fn sinh(self) -> Self;
589                fn sqrt(self) -> Self;
590                fn tan(self) -> Self;
591                fn tanh(self) -> Self;
592                fn trunc(self) -> Self;
593            }
594        }
595
596        impl PrimitiveFloatRef<$Float> for &$Float {}
597    }
598}
599
600impl_float!(f32, f32_consts, u32);
601impl_float!(f64, f64_consts, u64);
602
603// NOTE: the extra module level here is to make sure that `PrimitiveFloat` isn't in scope, so we
604// can be sure that we're not recursing. Elsewhere we rely on the normal `unconditional-recursion`
605// lint, but that doesn't see through this level of trait indirection.
606mod internal {
607    macro_rules! impl_float_to_int {
608        ($Float:ty => $($Int:ty),+) => {
609            $(
610                impl super::PrimitiveFloatToInt<$Int> for $Float {
611                    #[inline]
612                    #[expect(private_interfaces)]
613                    unsafe fn __to_int_unchecked(x: Self, _: super::SealedToken) -> $Int {
614                        // SAFETY: we're just passing through here!
615                        unsafe { <$Float>::to_int_unchecked::<$Int>(x) }
616                    }
617                }
618            )+
619        }
620    }
621
622    impl_float_to_int!(f32 => u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
623    impl_float_to_int!(f64 => u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
624}