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