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