core/num/f16.rs
1//! Constants for the `f16` half-precision floating point type.
2//!
3//! *[See also the `f16` primitive type][f16].*
4//!
5//! Mathematically significant numbers are provided in the `consts` sub-module.
6//!
7//! For the constants defined directly in this module
8//! (as distinct from those defined in the `consts` sub-module),
9//! new code should instead use the associated constants
10//! defined directly on the `f16` type.
11
12#![unstable(feature = "f16", issue = "116909")]
13
14use crate::convert::FloatToInt;
15use crate::num::FpCategory;
16use crate::panic::const_assert;
17use crate::{intrinsics, mem};
18
19/// Basic mathematical constants.
20#[unstable(feature = "f16", issue = "116909")]
21pub mod consts {
22 // FIXME: replace with mathematical constants from cmath.
23
24 /// Archimedes' constant (π)
25 #[unstable(feature = "f16", issue = "116909")]
26 pub const PI: f16 = 3.14159265358979323846264338327950288_f16;
27
28 /// The full circle constant (τ)
29 ///
30 /// Equal to 2π.
31 #[unstable(feature = "f16", issue = "116909")]
32 pub const TAU: f16 = 6.28318530717958647692528676655900577_f16;
33
34 /// The golden ratio (φ)
35 #[unstable(feature = "f16", issue = "116909")]
36 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
37 pub const PHI: f16 = 1.618033988749894848204586834365638118_f16;
38
39 /// The Euler-Mascheroni constant (γ)
40 #[unstable(feature = "f16", issue = "116909")]
41 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
42 pub const EGAMMA: f16 = 0.577215664901532860606512090082402431_f16;
43
44 /// π/2
45 #[unstable(feature = "f16", issue = "116909")]
46 pub const FRAC_PI_2: f16 = 1.57079632679489661923132169163975144_f16;
47
48 /// π/3
49 #[unstable(feature = "f16", issue = "116909")]
50 pub const FRAC_PI_3: f16 = 1.04719755119659774615421446109316763_f16;
51
52 /// π/4
53 #[unstable(feature = "f16", issue = "116909")]
54 pub const FRAC_PI_4: f16 = 0.785398163397448309615660845819875721_f16;
55
56 /// π/6
57 #[unstable(feature = "f16", issue = "116909")]
58 pub const FRAC_PI_6: f16 = 0.52359877559829887307710723054658381_f16;
59
60 /// π/8
61 #[unstable(feature = "f16", issue = "116909")]
62 pub const FRAC_PI_8: f16 = 0.39269908169872415480783042290993786_f16;
63
64 /// 1/π
65 #[unstable(feature = "f16", issue = "116909")]
66 pub const FRAC_1_PI: f16 = 0.318309886183790671537767526745028724_f16;
67
68 /// 1/sqrt(π)
69 #[unstable(feature = "f16", issue = "116909")]
70 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
71 pub const FRAC_1_SQRT_PI: f16 = 0.564189583547756286948079451560772586_f16;
72
73 /// 1/sqrt(2π)
74 #[doc(alias = "FRAC_1_SQRT_TAU")]
75 #[unstable(feature = "f16", issue = "116909")]
76 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
77 pub const FRAC_1_SQRT_2PI: f16 = 0.398942280401432677939946059934381868_f16;
78
79 /// 2/π
80 #[unstable(feature = "f16", issue = "116909")]
81 pub const FRAC_2_PI: f16 = 0.636619772367581343075535053490057448_f16;
82
83 /// 2/sqrt(π)
84 #[unstable(feature = "f16", issue = "116909")]
85 pub const FRAC_2_SQRT_PI: f16 = 1.12837916709551257389615890312154517_f16;
86
87 /// sqrt(2)
88 #[unstable(feature = "f16", issue = "116909")]
89 pub const SQRT_2: f16 = 1.41421356237309504880168872420969808_f16;
90
91 /// 1/sqrt(2)
92 #[unstable(feature = "f16", issue = "116909")]
93 pub const FRAC_1_SQRT_2: f16 = 0.707106781186547524400844362104849039_f16;
94
95 /// sqrt(3)
96 #[unstable(feature = "f16", issue = "116909")]
97 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
98 pub const SQRT_3: f16 = 1.732050807568877293527446341505872367_f16;
99
100 /// 1/sqrt(3)
101 #[unstable(feature = "f16", issue = "116909")]
102 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
103 pub const FRAC_1_SQRT_3: f16 = 0.577350269189625764509148780501957456_f16;
104
105 /// Euler's number (e)
106 #[unstable(feature = "f16", issue = "116909")]
107 pub const E: f16 = 2.71828182845904523536028747135266250_f16;
108
109 /// log<sub>2</sub>(10)
110 #[unstable(feature = "f16", issue = "116909")]
111 pub const LOG2_10: f16 = 3.32192809488736234787031942948939018_f16;
112
113 /// log<sub>2</sub>(e)
114 #[unstable(feature = "f16", issue = "116909")]
115 pub const LOG2_E: f16 = 1.44269504088896340735992468100189214_f16;
116
117 /// log<sub>10</sub>(2)
118 #[unstable(feature = "f16", issue = "116909")]
119 pub const LOG10_2: f16 = 0.301029995663981195213738894724493027_f16;
120
121 /// log<sub>10</sub>(e)
122 #[unstable(feature = "f16", issue = "116909")]
123 pub const LOG10_E: f16 = 0.434294481903251827651128918916605082_f16;
124
125 /// ln(2)
126 #[unstable(feature = "f16", issue = "116909")]
127 pub const LN_2: f16 = 0.693147180559945309417232121458176568_f16;
128
129 /// ln(10)
130 #[unstable(feature = "f16", issue = "116909")]
131 pub const LN_10: f16 = 2.30258509299404568401799145468436421_f16;
132}
133
134impl f16 {
135 // FIXME(f16_f128): almost all methods in this `impl` are missing examples and a const
136 // implementation. Add these once we can run code on all platforms and have f16/f128 in CTFE.
137
138 /// The radix or base of the internal representation of `f16`.
139 #[unstable(feature = "f16", issue = "116909")]
140 pub const RADIX: u32 = 2;
141
142 /// Number of significant digits in base 2.
143 ///
144 /// Note that the size of the mantissa in the bitwise representation is one
145 /// smaller than this since the leading 1 is not stored explicitly.
146 #[unstable(feature = "f16", issue = "116909")]
147 pub const MANTISSA_DIGITS: u32 = 11;
148
149 /// Approximate number of significant digits in base 10.
150 ///
151 /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
152 /// significant digits can be converted to `f16` and back without loss.
153 ///
154 /// Equal to floor(log<sub>10</sub> 2<sup>[`MANTISSA_DIGITS`] − 1</sup>).
155 ///
156 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
157 #[unstable(feature = "f16", issue = "116909")]
158 pub const DIGITS: u32 = 3;
159
160 /// [Machine epsilon] value for `f16`.
161 ///
162 /// This is the difference between `1.0` and the next larger representable number.
163 ///
164 /// Equal to 2<sup>1 − [`MANTISSA_DIGITS`]</sup>.
165 ///
166 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
167 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
168 #[unstable(feature = "f16", issue = "116909")]
169 pub const EPSILON: f16 = 9.7656e-4_f16;
170
171 /// Smallest finite `f16` value.
172 ///
173 /// Equal to −[`MAX`].
174 ///
175 /// [`MAX`]: f16::MAX
176 #[unstable(feature = "f16", issue = "116909")]
177 pub const MIN: f16 = -6.5504e+4_f16;
178 /// Smallest positive normal `f16` value.
179 ///
180 /// Equal to 2<sup>[`MIN_EXP`] − 1</sup>.
181 ///
182 /// [`MIN_EXP`]: f16::MIN_EXP
183 #[unstable(feature = "f16", issue = "116909")]
184 pub const MIN_POSITIVE: f16 = 6.1035e-5_f16;
185 /// Largest finite `f16` value.
186 ///
187 /// Equal to
188 /// (1 − 2<sup>−[`MANTISSA_DIGITS`]</sup>) 2<sup>[`MAX_EXP`]</sup>.
189 ///
190 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
191 /// [`MAX_EXP`]: f16::MAX_EXP
192 #[unstable(feature = "f16", issue = "116909")]
193 pub const MAX: f16 = 6.5504e+4_f16;
194
195 /// One greater than the minimum possible *normal* power of 2 exponent
196 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
197 ///
198 /// This corresponds to the exact minimum possible *normal* power of 2 exponent
199 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
200 /// In other words, all normal numbers representable by this type are
201 /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
202 #[unstable(feature = "f16", issue = "116909")]
203 pub const MIN_EXP: i32 = -13;
204 /// One greater than the maximum possible power of 2 exponent
205 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
206 ///
207 /// This corresponds to the exact maximum possible power of 2 exponent
208 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
209 /// In other words, all numbers representable by this type are
210 /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
211 #[unstable(feature = "f16", issue = "116909")]
212 pub const MAX_EXP: i32 = 16;
213
214 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
215 ///
216 /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]).
217 ///
218 /// [`MIN_POSITIVE`]: f16::MIN_POSITIVE
219 #[unstable(feature = "f16", issue = "116909")]
220 pub const MIN_10_EXP: i32 = -4;
221 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
222 ///
223 /// Equal to floor(log<sub>10</sub> [`MAX`]).
224 ///
225 /// [`MAX`]: f16::MAX
226 #[unstable(feature = "f16", issue = "116909")]
227 pub const MAX_10_EXP: i32 = 4;
228
229 /// Not a Number (NaN).
230 ///
231 /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
232 /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
233 /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
234 /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
235 /// info.
236 ///
237 /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
238 /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
239 /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
240 /// The concrete bit pattern may change across Rust versions and target platforms.
241 #[allow(clippy::eq_op)]
242 #[rustc_diagnostic_item = "f16_nan"]
243 #[unstable(feature = "f16", issue = "116909")]
244 pub const NAN: f16 = 0.0_f16 / 0.0_f16;
245
246 /// Infinity (∞).
247 #[unstable(feature = "f16", issue = "116909")]
248 pub const INFINITY: f16 = 1.0_f16 / 0.0_f16;
249
250 /// Negative infinity (−∞).
251 #[unstable(feature = "f16", issue = "116909")]
252 pub const NEG_INFINITY: f16 = -1.0_f16 / 0.0_f16;
253
254 /// Sign bit
255 pub(crate) const SIGN_MASK: u16 = 0x8000;
256
257 /// Exponent mask
258 pub(crate) const EXP_MASK: u16 = 0x7c00;
259
260 /// Mantissa mask
261 pub(crate) const MAN_MASK: u16 = 0x03ff;
262
263 /// Minimum representable positive value (min subnormal)
264 const TINY_BITS: u16 = 0x1;
265
266 /// Minimum representable negative value (min negative subnormal)
267 const NEG_TINY_BITS: u16 = Self::TINY_BITS | Self::SIGN_MASK;
268
269 /// Returns `true` if this value is NaN.
270 ///
271 /// ```
272 /// #![feature(f16)]
273 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
274 ///
275 /// let nan = f16::NAN;
276 /// let f = 7.0_f16;
277 ///
278 /// assert!(nan.is_nan());
279 /// assert!(!f.is_nan());
280 /// # }
281 /// ```
282 #[inline]
283 #[must_use]
284 #[unstable(feature = "f16", issue = "116909")]
285 #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
286 pub const fn is_nan(self) -> bool {
287 self != self
288 }
289
290 /// Returns `true` if this value is positive infinity or negative infinity, and
291 /// `false` otherwise.
292 ///
293 /// ```
294 /// #![feature(f16)]
295 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
296 ///
297 /// let f = 7.0f16;
298 /// let inf = f16::INFINITY;
299 /// let neg_inf = f16::NEG_INFINITY;
300 /// let nan = f16::NAN;
301 ///
302 /// assert!(!f.is_infinite());
303 /// assert!(!nan.is_infinite());
304 ///
305 /// assert!(inf.is_infinite());
306 /// assert!(neg_inf.is_infinite());
307 /// # }
308 /// ```
309 #[inline]
310 #[must_use]
311 #[unstable(feature = "f16", issue = "116909")]
312 pub const fn is_infinite(self) -> bool {
313 (self == f16::INFINITY) | (self == f16::NEG_INFINITY)
314 }
315
316 /// Returns `true` if this number is neither infinite nor NaN.
317 ///
318 /// ```
319 /// #![feature(f16)]
320 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
321 ///
322 /// let f = 7.0f16;
323 /// let inf: f16 = f16::INFINITY;
324 /// let neg_inf: f16 = f16::NEG_INFINITY;
325 /// let nan: f16 = f16::NAN;
326 ///
327 /// assert!(f.is_finite());
328 ///
329 /// assert!(!nan.is_finite());
330 /// assert!(!inf.is_finite());
331 /// assert!(!neg_inf.is_finite());
332 /// # }
333 /// ```
334 #[inline]
335 #[must_use]
336 #[unstable(feature = "f16", issue = "116909")]
337 #[rustc_const_unstable(feature = "f16", issue = "116909")]
338 pub const fn is_finite(self) -> bool {
339 // There's no need to handle NaN separately: if self is NaN,
340 // the comparison is not true, exactly as desired.
341 self.abs() < Self::INFINITY
342 }
343
344 /// Returns `true` if the number is [subnormal].
345 ///
346 /// ```
347 /// #![feature(f16)]
348 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
349 ///
350 /// let min = f16::MIN_POSITIVE; // 6.1035e-5
351 /// let max = f16::MAX;
352 /// let lower_than_min = 1.0e-7_f16;
353 /// let zero = 0.0_f16;
354 ///
355 /// assert!(!min.is_subnormal());
356 /// assert!(!max.is_subnormal());
357 ///
358 /// assert!(!zero.is_subnormal());
359 /// assert!(!f16::NAN.is_subnormal());
360 /// assert!(!f16::INFINITY.is_subnormal());
361 /// // Values between `0` and `min` are Subnormal.
362 /// assert!(lower_than_min.is_subnormal());
363 /// # }
364 /// ```
365 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
366 #[inline]
367 #[must_use]
368 #[unstable(feature = "f16", issue = "116909")]
369 pub const fn is_subnormal(self) -> bool {
370 matches!(self.classify(), FpCategory::Subnormal)
371 }
372
373 /// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
374 ///
375 /// ```
376 /// #![feature(f16)]
377 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
378 ///
379 /// let min = f16::MIN_POSITIVE; // 6.1035e-5
380 /// let max = f16::MAX;
381 /// let lower_than_min = 1.0e-7_f16;
382 /// let zero = 0.0_f16;
383 ///
384 /// assert!(min.is_normal());
385 /// assert!(max.is_normal());
386 ///
387 /// assert!(!zero.is_normal());
388 /// assert!(!f16::NAN.is_normal());
389 /// assert!(!f16::INFINITY.is_normal());
390 /// // Values between `0` and `min` are Subnormal.
391 /// assert!(!lower_than_min.is_normal());
392 /// # }
393 /// ```
394 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
395 #[inline]
396 #[must_use]
397 #[unstable(feature = "f16", issue = "116909")]
398 pub const fn is_normal(self) -> bool {
399 matches!(self.classify(), FpCategory::Normal)
400 }
401
402 /// Returns the floating point category of the number. If only one property
403 /// is going to be tested, it is generally faster to use the specific
404 /// predicate instead.
405 ///
406 /// ```
407 /// #![feature(f16)]
408 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
409 ///
410 /// use std::num::FpCategory;
411 ///
412 /// let num = 12.4_f16;
413 /// let inf = f16::INFINITY;
414 ///
415 /// assert_eq!(num.classify(), FpCategory::Normal);
416 /// assert_eq!(inf.classify(), FpCategory::Infinite);
417 /// # }
418 /// ```
419 #[inline]
420 #[unstable(feature = "f16", issue = "116909")]
421 pub const fn classify(self) -> FpCategory {
422 let b = self.to_bits();
423 match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
424 (0, Self::EXP_MASK) => FpCategory::Infinite,
425 (_, Self::EXP_MASK) => FpCategory::Nan,
426 (0, 0) => FpCategory::Zero,
427 (_, 0) => FpCategory::Subnormal,
428 _ => FpCategory::Normal,
429 }
430 }
431
432 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
433 /// positive sign bit and positive infinity.
434 ///
435 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
436 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
437 /// conserved over arithmetic operations, the result of `is_sign_positive` on
438 /// a NaN might produce an unexpected or non-portable result. See the [specification
439 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
440 /// if you need fully portable behavior (will return `false` for all NaNs).
441 ///
442 /// ```
443 /// #![feature(f16)]
444 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
445 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
446 ///
447 /// let f = 7.0_f16;
448 /// let g = -7.0_f16;
449 ///
450 /// assert!(f.is_sign_positive());
451 /// assert!(!g.is_sign_positive());
452 /// # }
453 /// ```
454 #[inline]
455 #[must_use]
456 #[unstable(feature = "f16", issue = "116909")]
457 pub const fn is_sign_positive(self) -> bool {
458 !self.is_sign_negative()
459 }
460
461 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
462 /// negative sign bit and negative infinity.
463 ///
464 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
465 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
466 /// conserved over arithmetic operations, the result of `is_sign_negative` on
467 /// a NaN might produce an unexpected or non-portable result. See the [specification
468 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
469 /// if you need fully portable behavior (will return `false` for all NaNs).
470 ///
471 /// ```
472 /// #![feature(f16)]
473 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
474 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
475 ///
476 /// let f = 7.0_f16;
477 /// let g = -7.0_f16;
478 ///
479 /// assert!(!f.is_sign_negative());
480 /// assert!(g.is_sign_negative());
481 /// # }
482 /// ```
483 #[inline]
484 #[must_use]
485 #[unstable(feature = "f16", issue = "116909")]
486 pub const fn is_sign_negative(self) -> bool {
487 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
488 // applies to zeros and NaNs as well.
489 // SAFETY: This is just transmuting to get the sign bit, it's fine.
490 (self.to_bits() & (1 << 15)) != 0
491 }
492
493 /// Returns the least number greater than `self`.
494 ///
495 /// Let `TINY` be the smallest representable positive `f16`. Then,
496 /// - if `self.is_nan()`, this returns `self`;
497 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
498 /// - if `self` is `-TINY`, this returns -0.0;
499 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
500 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
501 /// - otherwise the unique least value greater than `self` is returned.
502 ///
503 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
504 /// is finite `x == x.next_up().next_down()` also holds.
505 ///
506 /// ```rust
507 /// #![feature(f16)]
508 /// # // FIXME(f16_f128): ABI issues on MSVC
509 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
510 ///
511 /// // f16::EPSILON is the difference between 1.0 and the next number up.
512 /// assert_eq!(1.0f16.next_up(), 1.0 + f16::EPSILON);
513 /// // But not for most numbers.
514 /// assert!(0.1f16.next_up() < 0.1 + f16::EPSILON);
515 /// assert_eq!(4356f16.next_up(), 4360.0);
516 /// # }
517 /// ```
518 ///
519 /// This operation corresponds to IEEE-754 `nextUp`.
520 ///
521 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
522 /// [`INFINITY`]: Self::INFINITY
523 /// [`MIN`]: Self::MIN
524 /// [`MAX`]: Self::MAX
525 #[inline]
526 #[doc(alias = "nextUp")]
527 #[unstable(feature = "f16", issue = "116909")]
528 pub const fn next_up(self) -> Self {
529 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
530 // denormals to zero. This is in general unsound and unsupported, but here
531 // we do our best to still produce the correct result on such targets.
532 let bits = self.to_bits();
533 if self.is_nan() || bits == Self::INFINITY.to_bits() {
534 return self;
535 }
536
537 let abs = bits & !Self::SIGN_MASK;
538 let next_bits = if abs == 0 {
539 Self::TINY_BITS
540 } else if bits == abs {
541 bits + 1
542 } else {
543 bits - 1
544 };
545 Self::from_bits(next_bits)
546 }
547
548 /// Returns the greatest number less than `self`.
549 ///
550 /// Let `TINY` be the smallest representable positive `f16`. Then,
551 /// - if `self.is_nan()`, this returns `self`;
552 /// - if `self` is [`INFINITY`], this returns [`MAX`];
553 /// - if `self` is `TINY`, this returns 0.0;
554 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
555 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
556 /// - otherwise the unique greatest value less than `self` is returned.
557 ///
558 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
559 /// is finite `x == x.next_down().next_up()` also holds.
560 ///
561 /// ```rust
562 /// #![feature(f16)]
563 /// # // FIXME(f16_f128): ABI issues on MSVC
564 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
565 ///
566 /// let x = 1.0f16;
567 /// // Clamp value into range [0, 1).
568 /// let clamped = x.clamp(0.0, 1.0f16.next_down());
569 /// assert!(clamped < 1.0);
570 /// assert_eq!(clamped.next_up(), 1.0);
571 /// # }
572 /// ```
573 ///
574 /// This operation corresponds to IEEE-754 `nextDown`.
575 ///
576 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
577 /// [`INFINITY`]: Self::INFINITY
578 /// [`MIN`]: Self::MIN
579 /// [`MAX`]: Self::MAX
580 #[inline]
581 #[doc(alias = "nextDown")]
582 #[unstable(feature = "f16", issue = "116909")]
583 pub const fn next_down(self) -> Self {
584 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
585 // denormals to zero. This is in general unsound and unsupported, but here
586 // we do our best to still produce the correct result on such targets.
587 let bits = self.to_bits();
588 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
589 return self;
590 }
591
592 let abs = bits & !Self::SIGN_MASK;
593 let next_bits = if abs == 0 {
594 Self::NEG_TINY_BITS
595 } else if bits == abs {
596 bits - 1
597 } else {
598 bits + 1
599 };
600 Self::from_bits(next_bits)
601 }
602
603 /// Takes the reciprocal (inverse) of a number, `1/x`.
604 ///
605 /// ```
606 /// #![feature(f16)]
607 /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
608 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
609 ///
610 /// let x = 2.0_f16;
611 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
612 ///
613 /// assert!(abs_difference <= f16::EPSILON);
614 /// # }
615 /// ```
616 #[inline]
617 #[unstable(feature = "f16", issue = "116909")]
618 #[must_use = "this returns the result of the operation, without modifying the original"]
619 pub const fn recip(self) -> Self {
620 1.0 / self
621 }
622
623 /// Converts radians to degrees.
624 ///
625 /// ```
626 /// #![feature(f16)]
627 /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
628 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
629 ///
630 /// let angle = std::f16::consts::PI;
631 ///
632 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
633 /// assert!(abs_difference <= 0.5);
634 /// # }
635 /// ```
636 #[inline]
637 #[unstable(feature = "f16", issue = "116909")]
638 #[must_use = "this returns the result of the operation, without modifying the original"]
639 pub const fn to_degrees(self) -> Self {
640 // Use a literal for better precision.
641 const PIS_IN_180: f16 = 57.2957795130823208767981548141051703_f16;
642 self * PIS_IN_180
643 }
644
645 /// Converts degrees to radians.
646 ///
647 /// ```
648 /// #![feature(f16)]
649 /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
650 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
651 ///
652 /// let angle = 180.0f16;
653 ///
654 /// let abs_difference = (angle.to_radians() - std::f16::consts::PI).abs();
655 ///
656 /// assert!(abs_difference <= 0.01);
657 /// # }
658 /// ```
659 #[inline]
660 #[unstable(feature = "f16", issue = "116909")]
661 #[must_use = "this returns the result of the operation, without modifying the original"]
662 pub const fn to_radians(self) -> f16 {
663 // Use a literal for better precision.
664 const RADS_PER_DEG: f16 = 0.017453292519943295769236907684886_f16;
665 self * RADS_PER_DEG
666 }
667
668 /// Returns the maximum of the two numbers, ignoring NaN.
669 ///
670 /// If one of the arguments is NaN, then the other argument is returned.
671 /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
672 /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
673 /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
674 /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
675 ///
676 /// ```
677 /// #![feature(f16)]
678 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
679 ///
680 /// let x = 1.0f16;
681 /// let y = 2.0f16;
682 ///
683 /// assert_eq!(x.max(y), y);
684 /// # }
685 /// ```
686 #[inline]
687 #[unstable(feature = "f16", issue = "116909")]
688 #[rustc_const_unstable(feature = "f16", issue = "116909")]
689 #[must_use = "this returns the result of the comparison, without modifying either input"]
690 pub const fn max(self, other: f16) -> f16 {
691 intrinsics::maxnumf16(self, other)
692 }
693
694 /// Returns the minimum of the two numbers, ignoring NaN.
695 ///
696 /// If one of the arguments is NaN, then the other argument is returned.
697 /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
698 /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
699 /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
700 /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
701 ///
702 /// ```
703 /// #![feature(f16)]
704 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
705 ///
706 /// let x = 1.0f16;
707 /// let y = 2.0f16;
708 ///
709 /// assert_eq!(x.min(y), x);
710 /// # }
711 /// ```
712 #[inline]
713 #[unstable(feature = "f16", issue = "116909")]
714 #[rustc_const_unstable(feature = "f16", issue = "116909")]
715 #[must_use = "this returns the result of the comparison, without modifying either input"]
716 pub const fn min(self, other: f16) -> f16 {
717 intrinsics::minnumf16(self, other)
718 }
719
720 /// Returns the maximum of the two numbers, propagating NaN.
721 ///
722 /// This returns NaN when *either* argument is NaN, as opposed to
723 /// [`f16::max`] which only returns NaN when *both* arguments are NaN.
724 ///
725 /// ```
726 /// #![feature(f16)]
727 /// #![feature(float_minimum_maximum)]
728 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
729 ///
730 /// let x = 1.0f16;
731 /// let y = 2.0f16;
732 ///
733 /// assert_eq!(x.maximum(y), y);
734 /// assert!(x.maximum(f16::NAN).is_nan());
735 /// # }
736 /// ```
737 ///
738 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
739 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
740 /// Note that this follows the semantics specified in IEEE 754-2019.
741 ///
742 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
743 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
744 #[inline]
745 #[unstable(feature = "f16", issue = "116909")]
746 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
747 #[must_use = "this returns the result of the comparison, without modifying either input"]
748 pub const fn maximum(self, other: f16) -> f16 {
749 intrinsics::maximumf16(self, other)
750 }
751
752 /// Returns the minimum of the two numbers, propagating NaN.
753 ///
754 /// This returns NaN when *either* argument is NaN, as opposed to
755 /// [`f16::min`] which only returns NaN when *both* arguments are NaN.
756 ///
757 /// ```
758 /// #![feature(f16)]
759 /// #![feature(float_minimum_maximum)]
760 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
761 ///
762 /// let x = 1.0f16;
763 /// let y = 2.0f16;
764 ///
765 /// assert_eq!(x.minimum(y), x);
766 /// assert!(x.minimum(f16::NAN).is_nan());
767 /// # }
768 /// ```
769 ///
770 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
771 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
772 /// Note that this follows the semantics specified in IEEE 754-2019.
773 ///
774 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
775 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
776 #[inline]
777 #[unstable(feature = "f16", issue = "116909")]
778 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
779 #[must_use = "this returns the result of the comparison, without modifying either input"]
780 pub const fn minimum(self, other: f16) -> f16 {
781 intrinsics::minimumf16(self, other)
782 }
783
784 /// Calculates the midpoint (average) between `self` and `rhs`.
785 ///
786 /// This returns NaN when *either* argument is NaN or if a combination of
787 /// +inf and -inf is provided as arguments.
788 ///
789 /// # Examples
790 ///
791 /// ```
792 /// #![feature(f16)]
793 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
794 ///
795 /// assert_eq!(1f16.midpoint(4.0), 2.5);
796 /// assert_eq!((-5.5f16).midpoint(8.0), 1.25);
797 /// # }
798 /// ```
799 #[inline]
800 #[doc(alias = "average")]
801 #[unstable(feature = "f16", issue = "116909")]
802 #[rustc_const_unstable(feature = "f16", issue = "116909")]
803 pub const fn midpoint(self, other: f16) -> f16 {
804 const LO: f16 = f16::MIN_POSITIVE * 2.;
805 const HI: f16 = f16::MAX / 2.;
806
807 let (a, b) = (self, other);
808 let abs_a = a.abs();
809 let abs_b = b.abs();
810
811 if abs_a <= HI && abs_b <= HI {
812 // Overflow is impossible
813 (a + b) / 2.
814 } else if abs_a < LO {
815 // Not safe to halve `a` (would underflow)
816 a + (b / 2.)
817 } else if abs_b < LO {
818 // Not safe to halve `b` (would underflow)
819 (a / 2.) + b
820 } else {
821 // Safe to halve `a` and `b`
822 (a / 2.) + (b / 2.)
823 }
824 }
825
826 /// Rounds toward zero and converts to any primitive integer type,
827 /// assuming that the value is finite and fits in that type.
828 ///
829 /// ```
830 /// #![feature(f16)]
831 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
832 ///
833 /// let value = 4.6_f16;
834 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
835 /// assert_eq!(rounded, 4);
836 ///
837 /// let value = -128.9_f16;
838 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
839 /// assert_eq!(rounded, i8::MIN);
840 /// # }
841 /// ```
842 ///
843 /// # Safety
844 ///
845 /// The value must:
846 ///
847 /// * Not be `NaN`
848 /// * Not be infinite
849 /// * Be representable in the return type `Int`, after truncating off its fractional part
850 #[inline]
851 #[unstable(feature = "f16", issue = "116909")]
852 #[must_use = "this returns the result of the operation, without modifying the original"]
853 pub unsafe fn to_int_unchecked<Int>(self) -> Int
854 where
855 Self: FloatToInt<Int>,
856 {
857 // SAFETY: the caller must uphold the safety contract for
858 // `FloatToInt::to_int_unchecked`.
859 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
860 }
861
862 /// Raw transmutation to `u16`.
863 ///
864 /// This is currently identical to `transmute::<f16, u16>(self)` on all platforms.
865 ///
866 /// See [`from_bits`](#method.from_bits) for some discussion of the
867 /// portability of this operation (there are almost no issues).
868 ///
869 /// Note that this function is distinct from `as` casting, which attempts to
870 /// preserve the *numeric* value, and not the bitwise value.
871 ///
872 /// ```
873 /// #![feature(f16)]
874 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
875 ///
876 /// # // FIXME(f16_f128): enable this once const casting works
877 /// # // assert_ne!((1f16).to_bits(), 1f16 as u128); // to_bits() is not casting!
878 /// assert_eq!((12.5f16).to_bits(), 0x4a40);
879 /// # }
880 /// ```
881 #[inline]
882 #[unstable(feature = "f16", issue = "116909")]
883 #[must_use = "this returns the result of the operation, without modifying the original"]
884 #[allow(unnecessary_transmutes)]
885 pub const fn to_bits(self) -> u16 {
886 // SAFETY: `u16` is a plain old datatype so we can always transmute to it.
887 unsafe { mem::transmute(self) }
888 }
889
890 /// Raw transmutation from `u16`.
891 ///
892 /// This is currently identical to `transmute::<u16, f16>(v)` on all platforms.
893 /// It turns out this is incredibly portable, for two reasons:
894 ///
895 /// * Floats and Ints have the same endianness on all supported platforms.
896 /// * IEEE 754 very precisely specifies the bit layout of floats.
897 ///
898 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
899 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
900 /// (notably x86 and ARM) picked the interpretation that was ultimately
901 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
902 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
903 ///
904 /// Rather than trying to preserve signaling-ness cross-platform, this
905 /// implementation favors preserving the exact bits. This means that
906 /// any payloads encoded in NaNs will be preserved even if the result of
907 /// this method is sent over the network from an x86 machine to a MIPS one.
908 ///
909 /// If the results of this method are only manipulated by the same
910 /// architecture that produced them, then there is no portability concern.
911 ///
912 /// If the input isn't NaN, then there is no portability concern.
913 ///
914 /// If you don't care about signalingness (very likely), then there is no
915 /// portability concern.
916 ///
917 /// Note that this function is distinct from `as` casting, which attempts to
918 /// preserve the *numeric* value, and not the bitwise value.
919 ///
920 /// ```
921 /// #![feature(f16)]
922 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
923 ///
924 /// let v = f16::from_bits(0x4a40);
925 /// assert_eq!(v, 12.5);
926 /// # }
927 /// ```
928 #[inline]
929 #[must_use]
930 #[unstable(feature = "f16", issue = "116909")]
931 #[allow(unnecessary_transmutes)]
932 pub const fn from_bits(v: u16) -> Self {
933 // It turns out the safety issues with sNaN were overblown! Hooray!
934 // SAFETY: `u16` is a plain old datatype so we can always transmute from it.
935 unsafe { mem::transmute(v) }
936 }
937
938 /// Returns the memory representation of this floating point number as a byte array in
939 /// big-endian (network) byte order.
940 ///
941 /// See [`from_bits`](Self::from_bits) for some discussion of the
942 /// portability of this operation (there are almost no issues).
943 ///
944 /// # Examples
945 ///
946 /// ```
947 /// #![feature(f16)]
948 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
949 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
950 ///
951 /// let bytes = 12.5f16.to_be_bytes();
952 /// assert_eq!(bytes, [0x4a, 0x40]);
953 /// # }
954 /// ```
955 #[inline]
956 #[unstable(feature = "f16", issue = "116909")]
957 #[must_use = "this returns the result of the operation, without modifying the original"]
958 pub const fn to_be_bytes(self) -> [u8; 2] {
959 self.to_bits().to_be_bytes()
960 }
961
962 /// Returns the memory representation of this floating point number as a byte array in
963 /// little-endian byte order.
964 ///
965 /// See [`from_bits`](Self::from_bits) for some discussion of the
966 /// portability of this operation (there are almost no issues).
967 ///
968 /// # Examples
969 ///
970 /// ```
971 /// #![feature(f16)]
972 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
973 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
974 ///
975 /// let bytes = 12.5f16.to_le_bytes();
976 /// assert_eq!(bytes, [0x40, 0x4a]);
977 /// # }
978 /// ```
979 #[inline]
980 #[unstable(feature = "f16", issue = "116909")]
981 #[must_use = "this returns the result of the operation, without modifying the original"]
982 pub const fn to_le_bytes(self) -> [u8; 2] {
983 self.to_bits().to_le_bytes()
984 }
985
986 /// Returns the memory representation of this floating point number as a byte array in
987 /// native byte order.
988 ///
989 /// As the target platform's native endianness is used, portable code
990 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
991 ///
992 /// [`to_be_bytes`]: f16::to_be_bytes
993 /// [`to_le_bytes`]: f16::to_le_bytes
994 ///
995 /// See [`from_bits`](Self::from_bits) for some discussion of the
996 /// portability of this operation (there are almost no issues).
997 ///
998 /// # Examples
999 ///
1000 /// ```
1001 /// #![feature(f16)]
1002 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
1003 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1004 ///
1005 /// let bytes = 12.5f16.to_ne_bytes();
1006 /// assert_eq!(
1007 /// bytes,
1008 /// if cfg!(target_endian = "big") {
1009 /// [0x4a, 0x40]
1010 /// } else {
1011 /// [0x40, 0x4a]
1012 /// }
1013 /// );
1014 /// # }
1015 /// ```
1016 #[inline]
1017 #[unstable(feature = "f16", issue = "116909")]
1018 #[must_use = "this returns the result of the operation, without modifying the original"]
1019 pub const fn to_ne_bytes(self) -> [u8; 2] {
1020 self.to_bits().to_ne_bytes()
1021 }
1022
1023 /// Creates a floating point value from its representation as a byte array in big endian.
1024 ///
1025 /// See [`from_bits`](Self::from_bits) for some discussion of the
1026 /// portability of this operation (there are almost no issues).
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
1031 /// #![feature(f16)]
1032 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1033 ///
1034 /// let value = f16::from_be_bytes([0x4a, 0x40]);
1035 /// assert_eq!(value, 12.5);
1036 /// # }
1037 /// ```
1038 #[inline]
1039 #[must_use]
1040 #[unstable(feature = "f16", issue = "116909")]
1041 pub const fn from_be_bytes(bytes: [u8; 2]) -> Self {
1042 Self::from_bits(u16::from_be_bytes(bytes))
1043 }
1044
1045 /// Creates a floating point value from its representation as a byte array in little endian.
1046 ///
1047 /// See [`from_bits`](Self::from_bits) for some discussion of the
1048 /// portability of this operation (there are almost no issues).
1049 ///
1050 /// # Examples
1051 ///
1052 /// ```
1053 /// #![feature(f16)]
1054 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1055 ///
1056 /// let value = f16::from_le_bytes([0x40, 0x4a]);
1057 /// assert_eq!(value, 12.5);
1058 /// # }
1059 /// ```
1060 #[inline]
1061 #[must_use]
1062 #[unstable(feature = "f16", issue = "116909")]
1063 pub const fn from_le_bytes(bytes: [u8; 2]) -> Self {
1064 Self::from_bits(u16::from_le_bytes(bytes))
1065 }
1066
1067 /// Creates a floating point value from its representation as a byte array in native endian.
1068 ///
1069 /// As the target platform's native endianness is used, portable code
1070 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1071 /// appropriate instead.
1072 ///
1073 /// [`from_be_bytes`]: f16::from_be_bytes
1074 /// [`from_le_bytes`]: f16::from_le_bytes
1075 ///
1076 /// See [`from_bits`](Self::from_bits) for some discussion of the
1077 /// portability of this operation (there are almost no issues).
1078 ///
1079 /// # Examples
1080 ///
1081 /// ```
1082 /// #![feature(f16)]
1083 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1084 ///
1085 /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") {
1086 /// [0x4a, 0x40]
1087 /// } else {
1088 /// [0x40, 0x4a]
1089 /// });
1090 /// assert_eq!(value, 12.5);
1091 /// # }
1092 /// ```
1093 #[inline]
1094 #[must_use]
1095 #[unstable(feature = "f16", issue = "116909")]
1096 pub const fn from_ne_bytes(bytes: [u8; 2]) -> Self {
1097 Self::from_bits(u16::from_ne_bytes(bytes))
1098 }
1099
1100 /// Returns the ordering between `self` and `other`.
1101 ///
1102 /// Unlike the standard partial comparison between floating point numbers,
1103 /// this comparison always produces an ordering in accordance to
1104 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1105 /// floating point standard. The values are ordered in the following sequence:
1106 ///
1107 /// - negative quiet NaN
1108 /// - negative signaling NaN
1109 /// - negative infinity
1110 /// - negative numbers
1111 /// - negative subnormal numbers
1112 /// - negative zero
1113 /// - positive zero
1114 /// - positive subnormal numbers
1115 /// - positive numbers
1116 /// - positive infinity
1117 /// - positive signaling NaN
1118 /// - positive quiet NaN.
1119 ///
1120 /// The ordering established by this function does not always agree with the
1121 /// [`PartialOrd`] and [`PartialEq`] implementations of `f16`. For example,
1122 /// they consider negative and positive zero equal, while `total_cmp`
1123 /// doesn't.
1124 ///
1125 /// The interpretation of the signaling NaN bit follows the definition in
1126 /// the IEEE 754 standard, which may not match the interpretation by some of
1127 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1128 ///
1129 /// # Example
1130 ///
1131 /// ```
1132 /// #![feature(f16)]
1133 /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
1134 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1135 ///
1136 /// struct GoodBoy {
1137 /// name: &'static str,
1138 /// weight: f16,
1139 /// }
1140 ///
1141 /// let mut bois = vec![
1142 /// GoodBoy { name: "Pucci", weight: 0.1 },
1143 /// GoodBoy { name: "Woofer", weight: 99.0 },
1144 /// GoodBoy { name: "Yapper", weight: 10.0 },
1145 /// GoodBoy { name: "Chonk", weight: f16::INFINITY },
1146 /// GoodBoy { name: "Abs. Unit", weight: f16::NAN },
1147 /// GoodBoy { name: "Floaty", weight: -5.0 },
1148 /// ];
1149 ///
1150 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1151 ///
1152 /// // `f16::NAN` could be positive or negative, which will affect the sort order.
1153 /// if f16::NAN.is_sign_negative() {
1154 /// bois.into_iter().map(|b| b.weight)
1155 /// .zip([f16::NAN, -5.0, 0.1, 10.0, 99.0, f16::INFINITY].iter())
1156 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1157 /// } else {
1158 /// bois.into_iter().map(|b| b.weight)
1159 /// .zip([-5.0, 0.1, 10.0, 99.0, f16::INFINITY, f16::NAN].iter())
1160 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1161 /// }
1162 /// # }
1163 /// ```
1164 #[inline]
1165 #[must_use]
1166 #[unstable(feature = "f16", issue = "116909")]
1167 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1168 let mut left = self.to_bits() as i16;
1169 let mut right = other.to_bits() as i16;
1170
1171 // In case of negatives, flip all the bits except the sign
1172 // to achieve a similar layout as two's complement integers
1173 //
1174 // Why does this work? IEEE 754 floats consist of three fields:
1175 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1176 // fields as a whole have the property that their bitwise order is
1177 // equal to the numeric magnitude where the magnitude is defined.
1178 // The magnitude is not normally defined on NaN values, but
1179 // IEEE 754 totalOrder defines the NaN values also to follow the
1180 // bitwise order. This leads to order explained in the doc comment.
1181 // However, the representation of magnitude is the same for negative
1182 // and positive numbers – only the sign bit is different.
1183 // To easily compare the floats as signed integers, we need to
1184 // flip the exponent and mantissa bits in case of negative numbers.
1185 // We effectively convert the numbers to "two's complement" form.
1186 //
1187 // To do the flipping, we construct a mask and XOR against it.
1188 // We branchlessly calculate an "all-ones except for the sign bit"
1189 // mask from negative-signed values: right shifting sign-extends
1190 // the integer, so we "fill" the mask with sign bits, and then
1191 // convert to unsigned to push one more zero bit.
1192 // On positive values, the mask is all zeros, so it's a no-op.
1193 left ^= (((left >> 15) as u16) >> 1) as i16;
1194 right ^= (((right >> 15) as u16) >> 1) as i16;
1195
1196 left.cmp(&right)
1197 }
1198
1199 /// Restrict a value to a certain interval unless it is NaN.
1200 ///
1201 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1202 /// less than `min`. Otherwise this returns `self`.
1203 ///
1204 /// Note that this function returns NaN if the initial value was NaN as
1205 /// well.
1206 ///
1207 /// # Panics
1208 ///
1209 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1210 ///
1211 /// # Examples
1212 ///
1213 /// ```
1214 /// #![feature(f16)]
1215 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1216 ///
1217 /// assert!((-3.0f16).clamp(-2.0, 1.0) == -2.0);
1218 /// assert!((0.0f16).clamp(-2.0, 1.0) == 0.0);
1219 /// assert!((2.0f16).clamp(-2.0, 1.0) == 1.0);
1220 /// assert!((f16::NAN).clamp(-2.0, 1.0).is_nan());
1221 /// # }
1222 /// ```
1223 #[inline]
1224 #[unstable(feature = "f16", issue = "116909")]
1225 #[must_use = "method returns a new number and does not mutate the original value"]
1226 pub const fn clamp(mut self, min: f16, max: f16) -> f16 {
1227 const_assert!(
1228 min <= max,
1229 "min > max, or either was NaN",
1230 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1231 min: f16,
1232 max: f16,
1233 );
1234
1235 if self < min {
1236 self = min;
1237 }
1238 if self > max {
1239 self = max;
1240 }
1241 self
1242 }
1243
1244 /// Computes the absolute value of `self`.
1245 ///
1246 /// This function always returns the precise result.
1247 ///
1248 /// # Examples
1249 ///
1250 /// ```
1251 /// #![feature(f16)]
1252 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1253 ///
1254 /// let x = 3.5_f16;
1255 /// let y = -3.5_f16;
1256 ///
1257 /// assert_eq!(x.abs(), x);
1258 /// assert_eq!(y.abs(), -y);
1259 ///
1260 /// assert!(f16::NAN.abs().is_nan());
1261 /// # }
1262 /// ```
1263 #[inline]
1264 #[unstable(feature = "f16", issue = "116909")]
1265 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1266 #[must_use = "method returns a new number and does not mutate the original value"]
1267 pub const fn abs(self) -> Self {
1268 // FIXME(f16_f128): replace with `intrinsics::fabsf16` when available
1269 Self::from_bits(self.to_bits() & !(1 << 15))
1270 }
1271
1272 /// Returns a number that represents the sign of `self`.
1273 ///
1274 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1275 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1276 /// - NaN if the number is NaN
1277 ///
1278 /// # Examples
1279 ///
1280 /// ```
1281 /// #![feature(f16)]
1282 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1283 ///
1284 /// let f = 3.5_f16;
1285 ///
1286 /// assert_eq!(f.signum(), 1.0);
1287 /// assert_eq!(f16::NEG_INFINITY.signum(), -1.0);
1288 ///
1289 /// assert!(f16::NAN.signum().is_nan());
1290 /// # }
1291 /// ```
1292 #[inline]
1293 #[unstable(feature = "f16", issue = "116909")]
1294 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1295 #[must_use = "method returns a new number and does not mutate the original value"]
1296 pub const fn signum(self) -> f16 {
1297 if self.is_nan() { Self::NAN } else { 1.0_f16.copysign(self) }
1298 }
1299
1300 /// Returns a number composed of the magnitude of `self` and the sign of
1301 /// `sign`.
1302 ///
1303 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1304 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1305 /// returned.
1306 ///
1307 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1308 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1309 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1310 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1311 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1312 /// info.
1313 ///
1314 /// # Examples
1315 ///
1316 /// ```
1317 /// #![feature(f16)]
1318 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1319 ///
1320 /// let f = 3.5_f16;
1321 ///
1322 /// assert_eq!(f.copysign(0.42), 3.5_f16);
1323 /// assert_eq!(f.copysign(-0.42), -3.5_f16);
1324 /// assert_eq!((-f).copysign(0.42), 3.5_f16);
1325 /// assert_eq!((-f).copysign(-0.42), -3.5_f16);
1326 ///
1327 /// assert!(f16::NAN.copysign(1.0).is_nan());
1328 /// # }
1329 /// ```
1330 #[inline]
1331 #[unstable(feature = "f16", issue = "116909")]
1332 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1333 #[must_use = "method returns a new number and does not mutate the original value"]
1334 pub const fn copysign(self, sign: f16) -> f16 {
1335 // SAFETY: this is actually a safe intrinsic
1336 unsafe { intrinsics::copysignf16(self, sign) }
1337 }
1338
1339 /// Float addition that allows optimizations based on algebraic rules.
1340 ///
1341 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1342 #[must_use = "method returns a new number and does not mutate the original value"]
1343 #[unstable(feature = "float_algebraic", issue = "136469")]
1344 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1345 #[inline]
1346 pub const fn algebraic_add(self, rhs: f16) -> f16 {
1347 intrinsics::fadd_algebraic(self, rhs)
1348 }
1349
1350 /// Float subtraction that allows optimizations based on algebraic rules.
1351 ///
1352 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1353 #[must_use = "method returns a new number and does not mutate the original value"]
1354 #[unstable(feature = "float_algebraic", issue = "136469")]
1355 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1356 #[inline]
1357 pub const fn algebraic_sub(self, rhs: f16) -> f16 {
1358 intrinsics::fsub_algebraic(self, rhs)
1359 }
1360
1361 /// Float multiplication that allows optimizations based on algebraic rules.
1362 ///
1363 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1364 #[must_use = "method returns a new number and does not mutate the original value"]
1365 #[unstable(feature = "float_algebraic", issue = "136469")]
1366 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1367 #[inline]
1368 pub const fn algebraic_mul(self, rhs: f16) -> f16 {
1369 intrinsics::fmul_algebraic(self, rhs)
1370 }
1371
1372 /// Float division that allows optimizations based on algebraic rules.
1373 ///
1374 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1375 #[must_use = "method returns a new number and does not mutate the original value"]
1376 #[unstable(feature = "float_algebraic", issue = "136469")]
1377 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1378 #[inline]
1379 pub const fn algebraic_div(self, rhs: f16) -> f16 {
1380 intrinsics::fdiv_algebraic(self, rhs)
1381 }
1382
1383 /// Float remainder that allows optimizations based on algebraic rules.
1384 ///
1385 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1386 #[must_use = "method returns a new number and does not mutate the original value"]
1387 #[unstable(feature = "float_algebraic", issue = "136469")]
1388 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1389 #[inline]
1390 pub const fn algebraic_rem(self, rhs: f16) -> f16 {
1391 intrinsics::frem_algebraic(self, rhs)
1392 }
1393}