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#![expect(clippy::approx_constant, reason = "this module defines f16 constants")]
14
15use crate::convert::{FloatToFloat, FloatToInt};
16use crate::num::FpCategory;
17#[cfg(not(test))]
18use crate::num::imp::libm;
19use crate::panic::const_assert;
20use crate::{intrinsics, mem};
21
22/// Basic mathematical constants.
23#[unstable(feature = "f16", issue = "116909")]
24#[rustc_diagnostic_item = "f16_consts_mod"]
25pub mod consts {
26 // FIXME: replace with mathematical constants from cmath.
27
28 /// Archimedes' constant (π)
29 #[unstable(feature = "f16", issue = "116909")]
30 pub const PI: f16 = 3.14159265358979323846264338327950288_f16;
31
32 /// The full circle constant (τ)
33 ///
34 /// Equal to 2π.
35 #[unstable(feature = "f16", issue = "116909")]
36 pub const TAU: f16 = 6.28318530717958647692528676655900577_f16;
37
38 /// The golden ratio (φ)
39 #[doc(alias = "phi")]
40 #[unstable(feature = "f16", issue = "116909")]
41 pub const GOLDEN_RATIO: f16 = 1.618033988749894848204586834365638118_f16;
42
43 /// The Euler-Mascheroni constant (γ)
44 #[unstable(feature = "f16", issue = "116909")]
45 pub const EULER_GAMMA: f16 = 0.577215664901532860606512090082402431_f16;
46
47 /// π/2
48 #[unstable(feature = "f16", issue = "116909")]
49 pub const FRAC_PI_2: f16 = 1.57079632679489661923132169163975144_f16;
50
51 /// π/3
52 #[unstable(feature = "f16", issue = "116909")]
53 pub const FRAC_PI_3: f16 = 1.04719755119659774615421446109316763_f16;
54
55 /// π/4
56 #[unstable(feature = "f16", issue = "116909")]
57 pub const FRAC_PI_4: f16 = 0.785398163397448309615660845819875721_f16;
58
59 /// π/6
60 #[unstable(feature = "f16", issue = "116909")]
61 pub const FRAC_PI_6: f16 = 0.52359877559829887307710723054658381_f16;
62
63 /// π/8
64 #[unstable(feature = "f16", issue = "116909")]
65 pub const FRAC_PI_8: f16 = 0.39269908169872415480783042290993786_f16;
66
67 /// 1/π
68 #[unstable(feature = "f16", issue = "116909")]
69 pub const FRAC_1_PI: f16 = 0.318309886183790671537767526745028724_f16;
70
71 /// 1/sqrt(π)
72 #[unstable(feature = "f16", issue = "116909")]
73 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
74 pub const FRAC_1_SQRT_PI: f16 = 0.564189583547756286948079451560772586_f16;
75
76 /// 1/sqrt(2π)
77 #[doc(alias = "FRAC_1_SQRT_TAU")]
78 #[unstable(feature = "f16", issue = "116909")]
79 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
80 pub const FRAC_1_SQRT_2PI: f16 = 0.398942280401432677939946059934381868_f16;
81
82 /// 2/π
83 #[unstable(feature = "f16", issue = "116909")]
84 pub const FRAC_2_PI: f16 = 0.636619772367581343075535053490057448_f16;
85
86 /// 2/sqrt(π)
87 #[unstable(feature = "f16", issue = "116909")]
88 pub const FRAC_2_SQRT_PI: f16 = 1.12837916709551257389615890312154517_f16;
89
90 /// sqrt(2)
91 #[unstable(feature = "f16", issue = "116909")]
92 pub const SQRT_2: f16 = 1.41421356237309504880168872420969808_f16;
93
94 /// 1/sqrt(2)
95 #[unstable(feature = "f16", issue = "116909")]
96 pub const FRAC_1_SQRT_2: f16 = 0.707106781186547524400844362104849039_f16;
97
98 /// sqrt(3)
99 #[unstable(feature = "f16", issue = "116909")]
100 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
101 pub const SQRT_3: f16 = 1.732050807568877293527446341505872367_f16;
102
103 /// 1/sqrt(3)
104 #[unstable(feature = "f16", issue = "116909")]
105 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
106 pub const FRAC_1_SQRT_3: f16 = 0.577350269189625764509148780501957456_f16;
107
108 /// sqrt(5)
109 #[unstable(feature = "more_float_constants", issue = "146939")]
110 // Also, #[unstable(feature = "f16", issue = "116909")]
111 pub const SQRT_5: f16 = 2.23606797749978969640917366873127623_f16;
112
113 /// 1/sqrt(5)
114 #[unstable(feature = "more_float_constants", issue = "146939")]
115 // Also, #[unstable(feature = "f16", issue = "116909")]
116 pub const FRAC_1_SQRT_5: f16 = 0.44721359549995793928183473374625524_f16;
117
118 /// Euler's number (e)
119 #[unstable(feature = "f16", issue = "116909")]
120 pub const E: f16 = 2.71828182845904523536028747135266250_f16;
121
122 /// log<sub>2</sub>(10)
123 #[unstable(feature = "f16", issue = "116909")]
124 pub const LOG2_10: f16 = 3.32192809488736234787031942948939018_f16;
125
126 /// log<sub>2</sub>(e)
127 #[unstable(feature = "f16", issue = "116909")]
128 pub const LOG2_E: f16 = 1.44269504088896340735992468100189214_f16;
129
130 /// log<sub>10</sub>(2)
131 #[unstable(feature = "f16", issue = "116909")]
132 pub const LOG10_2: f16 = 0.301029995663981195213738894724493027_f16;
133
134 /// log<sub>10</sub>(e)
135 #[unstable(feature = "f16", issue = "116909")]
136 pub const LOG10_E: f16 = 0.434294481903251827651128918916605082_f16;
137
138 /// ln(2)
139 #[unstable(feature = "f16", issue = "116909")]
140 pub const LN_2: f16 = 0.693147180559945309417232121458176568_f16;
141
142 /// ln(10)
143 #[unstable(feature = "f16", issue = "116909")]
144 pub const LN_10: f16 = 2.30258509299404568401799145468436421_f16;
145}
146
147#[doc(test(attr(
148 feature(cfg_target_has_reliable_f16_f128),
149 allow(internal_features, unused_features)
150)))]
151impl f16 {
152 /// The radix or base of the internal representation of `f16`.
153 #[unstable(feature = "f16", issue = "116909")]
154 pub const RADIX: u32 = 2;
155
156 /// The size of this float type in bits.
157 // #[unstable(feature = "f16", issue = "116909")]
158 #[unstable(feature = "float_bits_const", issue = "151073")]
159 pub const BITS: u32 = 16;
160
161 /// Number of significant digits in base 2.
162 ///
163 /// Note that the size of the mantissa in the bitwise representation is one
164 /// smaller than this since the leading 1 is not stored explicitly.
165 #[unstable(feature = "f16", issue = "116909")]
166 pub const MANTISSA_DIGITS: u32 = 11;
167
168 /// Approximate number of significant digits in base 10.
169 ///
170 /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
171 /// significant digits can be converted to `f16` and back without loss.
172 ///
173 /// Equal to floor(log<sub>10</sub> 2<sup>[`MANTISSA_DIGITS`] − 1</sup>).
174 ///
175 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
176 #[unstable(feature = "f16", issue = "116909")]
177 pub const DIGITS: u32 = 3;
178
179 /// [Machine epsilon] value for `f16`.
180 ///
181 /// This is the difference between `1.0` and the next larger representable number.
182 ///
183 /// Equal to 2<sup>1 − [`MANTISSA_DIGITS`]</sup>.
184 ///
185 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
186 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
187 #[unstable(feature = "f16", issue = "116909")]
188 #[rustc_diagnostic_item = "f16_epsilon"]
189 pub const EPSILON: f16 = 9.7656e-4_f16;
190
191 /// Smallest finite `f16` value.
192 ///
193 /// Equal to −[`MAX`].
194 ///
195 /// [`MAX`]: f16::MAX
196 #[unstable(feature = "f16", issue = "116909")]
197 pub const MIN: f16 = -6.5504e+4_f16;
198 /// Smallest positive normal `f16` value.
199 ///
200 /// Equal to 2<sup>[`MIN_EXP`] − 1</sup>.
201 ///
202 /// [`MIN_EXP`]: f16::MIN_EXP
203 #[unstable(feature = "f16", issue = "116909")]
204 pub const MIN_POSITIVE: f16 = 6.1035e-5_f16;
205 /// Largest finite `f16` value.
206 ///
207 /// Equal to
208 /// (1 − 2<sup>−[`MANTISSA_DIGITS`]</sup>) 2<sup>[`MAX_EXP`]</sup>.
209 ///
210 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
211 /// [`MAX_EXP`]: f16::MAX_EXP
212 #[unstable(feature = "f16", issue = "116909")]
213 pub const MAX: f16 = 6.5504e+4_f16;
214
215 /// One greater than the minimum possible *normal* power of 2 exponent
216 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
217 ///
218 /// This corresponds to the exact minimum possible *normal* power of 2 exponent
219 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
220 /// In other words, all normal numbers representable by this type are
221 /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
222 #[unstable(feature = "f16", issue = "116909")]
223 pub const MIN_EXP: i32 = -13;
224 /// One greater than the maximum possible power of 2 exponent
225 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
226 ///
227 /// This corresponds to the exact maximum possible power of 2 exponent
228 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
229 /// In other words, all numbers representable by this type are
230 /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
231 #[unstable(feature = "f16", issue = "116909")]
232 pub const MAX_EXP: i32 = 16;
233
234 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
235 ///
236 /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]).
237 ///
238 /// [`MIN_POSITIVE`]: f16::MIN_POSITIVE
239 #[unstable(feature = "f16", issue = "116909")]
240 pub const MIN_10_EXP: i32 = -4;
241 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
242 ///
243 /// Equal to floor(log<sub>10</sub> [`MAX`]).
244 ///
245 /// [`MAX`]: f16::MAX
246 #[unstable(feature = "f16", issue = "116909")]
247 pub const MAX_10_EXP: i32 = 4;
248
249 /// Not a Number (NaN).
250 ///
251 /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
252 /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
253 /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
254 /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
255 /// info.
256 ///
257 /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
258 /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
259 /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
260 /// The concrete bit pattern may change across Rust versions and target platforms.
261 #[allow(clippy::eq_op)]
262 #[rustc_diagnostic_item = "f16_nan"]
263 #[unstable(feature = "f16", issue = "116909")]
264 pub const NAN: f16 = 0.0_f16 / 0.0_f16;
265
266 /// Infinity (∞).
267 #[unstable(feature = "f16", issue = "116909")]
268 pub const INFINITY: f16 = 1.0_f16 / 0.0_f16;
269
270 /// Negative infinity (−∞).
271 #[unstable(feature = "f16", issue = "116909")]
272 pub const NEG_INFINITY: f16 = -1.0_f16 / 0.0_f16;
273
274 /// Maximum integer that can be represented exactly in an [`f16`] value,
275 /// with no other integer converting to the same floating point value.
276 ///
277 /// For an integer `x` which satisfies `MIN_EXACT_INTEGER <= x <= MAX_EXACT_INTEGER`,
278 /// there is a "one-to-one" mapping between [`i16`] and [`f16`] values.
279 /// `MAX_EXACT_INTEGER + 1` also converts losslessly to [`f16`] and back to
280 /// [`i16`], but `MAX_EXACT_INTEGER + 2` converts to the same [`f16`] value
281 /// (and back to `MAX_EXACT_INTEGER + 1` as an integer) so there is not a
282 /// "one-to-one" mapping.
283 ///
284 /// [`MAX_EXACT_INTEGER`]: f16::MAX_EXACT_INTEGER
285 /// [`MIN_EXACT_INTEGER`]: f16::MIN_EXACT_INTEGER
286 /// ```
287 /// #![feature(f16)]
288 /// #![feature(float_exact_integer_constants)]
289 /// # // FIXME(#152635): Float rounding on `i586` does not adhere to IEEE 754
290 /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] {
291 /// # #[cfg(target_has_reliable_f16)] {
292 /// let max_exact_int = f16::MAX_EXACT_INTEGER;
293 /// assert_eq!(max_exact_int, max_exact_int as f16 as i16);
294 /// assert_eq!(max_exact_int + 1, (max_exact_int + 1) as f16 as i16);
295 /// assert_ne!(max_exact_int + 2, (max_exact_int + 2) as f16 as i16);
296 ///
297 /// // Beyond `f16::MAX_EXACT_INTEGER`, multiple integers can map to one float value
298 /// assert_eq!((max_exact_int + 1) as f16, (max_exact_int + 2) as f16);
299 /// # }}
300 /// ```
301 // #[unstable(feature = "f16", issue = "116909")]
302 #[unstable(feature = "float_exact_integer_constants", issue = "152466")]
303 pub const MAX_EXACT_INTEGER: i16 = (1 << Self::MANTISSA_DIGITS) - 1;
304
305 /// Minimum integer that can be represented exactly in an [`f16`] value,
306 /// with no other integer converting to the same floating point value.
307 ///
308 /// For an integer `x` which satisfies `MIN_EXACT_INTEGER <= x <= MAX_EXACT_INTEGER`,
309 /// there is a "one-to-one" mapping between [`i16`] and [`f16`] values.
310 /// `MAX_EXACT_INTEGER + 1` also converts losslessly to [`f16`] and back to
311 /// [`i16`], but `MAX_EXACT_INTEGER + 2` converts to the same [`f16`] value
312 /// (and back to `MAX_EXACT_INTEGER + 1` as an integer) so there is not a
313 /// "one-to-one" mapping.
314 ///
315 /// This constant is equivalent to `-MAX_EXACT_INTEGER`.
316 ///
317 /// [`MAX_EXACT_INTEGER`]: f16::MAX_EXACT_INTEGER
318 /// [`MIN_EXACT_INTEGER`]: f16::MIN_EXACT_INTEGER
319 /// ```
320 /// #![feature(f16)]
321 /// #![feature(float_exact_integer_constants)]
322 /// # // FIXME(#152635): Float rounding on `i586` does not adhere to IEEE 754
323 /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] {
324 /// # #[cfg(target_has_reliable_f16)] {
325 /// let min_exact_int = f16::MIN_EXACT_INTEGER;
326 /// assert_eq!(min_exact_int, min_exact_int as f16 as i16);
327 /// assert_eq!(min_exact_int - 1, (min_exact_int - 1) as f16 as i16);
328 /// assert_ne!(min_exact_int - 2, (min_exact_int - 2) as f16 as i16);
329 ///
330 /// // Below `f16::MIN_EXACT_INTEGER`, multiple integers can map to one float value
331 /// assert_eq!((min_exact_int - 1) as f16, (min_exact_int - 2) as f16);
332 /// # }}
333 /// ```
334 // #[unstable(feature = "f16", issue = "116909")]
335 #[unstable(feature = "float_exact_integer_constants", issue = "152466")]
336 pub const MIN_EXACT_INTEGER: i16 = -Self::MAX_EXACT_INTEGER;
337
338 /// The mask of the bit used to encode the sign of an [`f16`].
339 ///
340 /// This bit is set when the sign is negative and unset when the sign is
341 /// positive.
342 /// If you only need to check whether a value is positive or negative,
343 /// [`is_sign_positive`] or [`is_sign_negative`] can be used.
344 ///
345 /// [`is_sign_positive`]: f16::is_sign_positive
346 /// [`is_sign_negative`]: f16::is_sign_negative
347 /// ```rust
348 /// #![feature(float_masks)]
349 /// #![feature(f16)]
350 /// # #[cfg(target_has_reliable_f16)] {
351 /// let sign_mask = f16::SIGN_MASK;
352 /// let a = 1.6552f16;
353 /// let a_bits = a.to_bits();
354 ///
355 /// assert_eq!(a_bits & sign_mask, 0x0);
356 /// assert_eq!(f16::from_bits(a_bits ^ sign_mask), -a);
357 /// assert_eq!(sign_mask, (-0.0f16).to_bits());
358 /// # }
359 /// ```
360 #[unstable(feature = "float_masks", issue = "154064")]
361 pub const SIGN_MASK: u16 = 0x8000;
362
363 /// The mask of the bits used to encode the exponent of an [`f16`].
364 ///
365 /// Note that the exponent is stored as a biased value, with a bias of 15 for `f16`.
366 ///
367 /// ```rust
368 /// #![feature(float_masks)]
369 /// #![feature(f16)]
370 /// # #[cfg(target_has_reliable_f16)] {
371 /// let exponent_mask = f16::EXPONENT_MASK;
372 ///
373 /// fn get_exp(a: f16) -> i16 {
374 /// let bias = 15;
375 /// let biased = a.to_bits() & f16::EXPONENT_MASK;
376 /// (biased >> (f16::MANTISSA_DIGITS - 1)).cast_signed() - bias
377 /// }
378 ///
379 /// assert_eq!(get_exp(0.5), -1);
380 /// assert_eq!(get_exp(1.0), 0);
381 /// assert_eq!(get_exp(2.0), 1);
382 /// assert_eq!(get_exp(4.0), 2);
383 /// # }
384 /// ```
385 #[unstable(feature = "float_masks", issue = "154064")]
386 pub const EXPONENT_MASK: u16 = 0x7c00;
387
388 /// The mask of the bits used to encode the mantissa of an [`f16`].
389 ///
390 /// ```rust
391 /// #![feature(float_masks)]
392 /// #![feature(f16)]
393 /// # #[cfg(target_has_reliable_f16)] {
394 /// let mantissa_mask = f16::MANTISSA_MASK;
395 ///
396 /// assert_eq!(0f16.to_bits() & mantissa_mask, 0x0);
397 /// assert_eq!(1f16.to_bits() & mantissa_mask, 0x0);
398 ///
399 /// // multiplying a finite value by a power of 2 doesn't change its mantissa
400 /// // unless the result or initial value is not normal.
401 /// let a = 1.6552f16;
402 /// let b = 4.0 * a;
403 /// assert_eq!(a.to_bits() & mantissa_mask, b.to_bits() & mantissa_mask);
404 ///
405 /// // The maximum and minimum values have a saturated significand
406 /// assert_eq!(f16::MAX.to_bits() & f16::MANTISSA_MASK, f16::MANTISSA_MASK);
407 /// assert_eq!(f16::MIN.to_bits() & f16::MANTISSA_MASK, f16::MANTISSA_MASK);
408 /// # }
409 /// ```
410 #[unstable(feature = "float_masks", issue = "154064")]
411 pub const MANTISSA_MASK: u16 = 0x03ff;
412
413 /// Minimum representable positive value (min subnormal)
414 const TINY_BITS: u16 = 0x1;
415
416 /// Minimum representable negative value (min negative subnormal)
417 const NEG_TINY_BITS: u16 = Self::TINY_BITS | Self::SIGN_MASK;
418
419 /// Returns `true` if this value is NaN.
420 ///
421 /// ```
422 /// #![feature(f16)]
423 /// # #[cfg(target_has_reliable_f16)] {
424 ///
425 /// let nan = f16::NAN;
426 /// let f = 7.0_f16;
427 ///
428 /// assert!(nan.is_nan());
429 /// assert!(!f.is_nan());
430 /// # }
431 /// ```
432 #[inline]
433 #[must_use]
434 #[unstable(feature = "f16", issue = "116909")]
435 #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
436 pub const fn is_nan(self) -> bool {
437 self != self
438 }
439
440 /// Returns `true` if this value is positive infinity or negative infinity, and
441 /// `false` otherwise.
442 ///
443 /// ```
444 /// #![feature(f16)]
445 /// # #[cfg(target_has_reliable_f16)] {
446 ///
447 /// let f = 7.0f16;
448 /// let inf = f16::INFINITY;
449 /// let neg_inf = f16::NEG_INFINITY;
450 /// let nan = f16::NAN;
451 ///
452 /// assert!(!f.is_infinite());
453 /// assert!(!nan.is_infinite());
454 ///
455 /// assert!(inf.is_infinite());
456 /// assert!(neg_inf.is_infinite());
457 /// # }
458 /// ```
459 #[inline]
460 #[must_use]
461 #[unstable(feature = "f16", issue = "116909")]
462 pub const fn is_infinite(self) -> bool {
463 (self == f16::INFINITY) | (self == f16::NEG_INFINITY)
464 }
465
466 /// Returns `true` if this number is neither infinite nor NaN.
467 ///
468 /// ```
469 /// #![feature(f16)]
470 /// # #[cfg(target_has_reliable_f16)] {
471 ///
472 /// let f = 7.0f16;
473 /// let inf: f16 = f16::INFINITY;
474 /// let neg_inf: f16 = f16::NEG_INFINITY;
475 /// let nan: f16 = f16::NAN;
476 ///
477 /// assert!(f.is_finite());
478 ///
479 /// assert!(!nan.is_finite());
480 /// assert!(!inf.is_finite());
481 /// assert!(!neg_inf.is_finite());
482 /// # }
483 /// ```
484 #[inline]
485 #[must_use]
486 #[unstable(feature = "f16", issue = "116909")]
487 #[rustc_const_unstable(feature = "f16", issue = "116909")]
488 pub const fn is_finite(self) -> bool {
489 // There's no need to handle NaN separately: if self is NaN,
490 // the comparison is not true, exactly as desired.
491 self.abs() < Self::INFINITY
492 }
493
494 /// Returns `true` if the number is [subnormal].
495 ///
496 /// ```
497 /// #![feature(f16)]
498 /// # #[cfg(target_has_reliable_f16)] {
499 ///
500 /// let min = f16::MIN_POSITIVE; // 6.1035e-5
501 /// let max = f16::MAX;
502 /// let lower_than_min = 1.0e-7_f16;
503 /// let zero = 0.0_f16;
504 ///
505 /// assert!(!min.is_subnormal());
506 /// assert!(!max.is_subnormal());
507 ///
508 /// assert!(!zero.is_subnormal());
509 /// assert!(!f16::NAN.is_subnormal());
510 /// assert!(!f16::INFINITY.is_subnormal());
511 /// // Values between `0` and `min` are Subnormal.
512 /// assert!(lower_than_min.is_subnormal());
513 /// # }
514 /// ```
515 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
516 #[inline]
517 #[must_use]
518 #[unstable(feature = "f16", issue = "116909")]
519 pub const fn is_subnormal(self) -> bool {
520 matches!(self.classify(), FpCategory::Subnormal)
521 }
522
523 /// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
524 ///
525 /// ```
526 /// #![feature(f16)]
527 /// # #[cfg(target_has_reliable_f16)] {
528 ///
529 /// let min = f16::MIN_POSITIVE; // 6.1035e-5
530 /// let max = f16::MAX;
531 /// let lower_than_min = 1.0e-7_f16;
532 /// let zero = 0.0_f16;
533 ///
534 /// assert!(min.is_normal());
535 /// assert!(max.is_normal());
536 ///
537 /// assert!(!zero.is_normal());
538 /// assert!(!f16::NAN.is_normal());
539 /// assert!(!f16::INFINITY.is_normal());
540 /// // Values between `0` and `min` are Subnormal.
541 /// assert!(!lower_than_min.is_normal());
542 /// # }
543 /// ```
544 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
545 #[inline]
546 #[must_use]
547 #[unstable(feature = "f16", issue = "116909")]
548 pub const fn is_normal(self) -> bool {
549 matches!(self.classify(), FpCategory::Normal)
550 }
551
552 /// Returns the floating point category of the number. If only one property
553 /// is going to be tested, it is generally faster to use the specific
554 /// predicate instead.
555 ///
556 /// ```
557 /// #![feature(f16)]
558 /// # #[cfg(target_has_reliable_f16)] {
559 ///
560 /// use std::num::FpCategory;
561 ///
562 /// let num = 12.4_f16;
563 /// let inf = f16::INFINITY;
564 ///
565 /// assert_eq!(num.classify(), FpCategory::Normal);
566 /// assert_eq!(inf.classify(), FpCategory::Infinite);
567 /// # }
568 /// ```
569 #[inline]
570 #[unstable(feature = "f16", issue = "116909")]
571 #[must_use]
572 pub const fn classify(self) -> FpCategory {
573 let b = self.to_bits();
574 match (b & Self::MANTISSA_MASK, b & Self::EXPONENT_MASK) {
575 (0, Self::EXPONENT_MASK) => FpCategory::Infinite,
576 (_, Self::EXPONENT_MASK) => FpCategory::Nan,
577 (0, 0) => FpCategory::Zero,
578 (_, 0) => FpCategory::Subnormal,
579 _ => FpCategory::Normal,
580 }
581 }
582
583 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
584 /// positive sign bit and positive infinity.
585 ///
586 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
587 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
588 /// conserved over arithmetic operations, the result of `is_sign_positive` on
589 /// a NaN might produce an unexpected or non-portable result. See the [specification
590 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
591 /// if you need fully portable behavior (will return `false` for all NaNs).
592 ///
593 /// ```
594 /// #![feature(f16)]
595 /// # #[cfg(target_has_reliable_f16)] {
596 ///
597 /// let f = 7.0_f16;
598 /// let g = -7.0_f16;
599 ///
600 /// assert!(f.is_sign_positive());
601 /// assert!(!g.is_sign_positive());
602 /// # }
603 /// ```
604 #[inline]
605 #[must_use]
606 #[unstable(feature = "f16", issue = "116909")]
607 pub const fn is_sign_positive(self) -> bool {
608 !self.is_sign_negative()
609 }
610
611 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
612 /// negative sign bit and negative infinity.
613 ///
614 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
615 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
616 /// conserved over arithmetic operations, the result of `is_sign_negative` on
617 /// a NaN might produce an unexpected or non-portable result. See the [specification
618 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
619 /// if you need fully portable behavior (will return `false` for all NaNs).
620 ///
621 /// ```
622 /// #![feature(f16)]
623 /// # #[cfg(target_has_reliable_f16)] {
624 ///
625 /// let f = 7.0_f16;
626 /// let g = -7.0_f16;
627 ///
628 /// assert!(!f.is_sign_negative());
629 /// assert!(g.is_sign_negative());
630 /// # }
631 /// ```
632 #[inline]
633 #[must_use]
634 #[unstable(feature = "f16", issue = "116909")]
635 pub const fn is_sign_negative(self) -> bool {
636 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
637 // applies to zeros and NaNs as well.
638 // SAFETY: This is just transmuting to get the sign bit, it's fine.
639 (self.to_bits() & (1 << 15)) != 0
640 }
641
642 /// Returns the least number greater than `self`.
643 ///
644 /// Let `TINY` be the smallest representable positive `f16`. Then,
645 /// - if `self.is_nan()`, this returns `self`;
646 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
647 /// - if `self` is `-TINY`, this returns -0.0;
648 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
649 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
650 /// - otherwise the unique least value greater than `self` is returned.
651 ///
652 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
653 /// is finite `x == x.next_up().next_down()` also holds.
654 ///
655 /// ```rust
656 /// #![feature(f16)]
657 /// # #[cfg(target_has_reliable_f16)] {
658 ///
659 /// // f16::EPSILON is the difference between 1.0 and the next number up.
660 /// assert_eq!(1.0f16.next_up(), 1.0 + f16::EPSILON);
661 /// // But not for most numbers.
662 /// assert!(0.1f16.next_up() < 0.1 + f16::EPSILON);
663 /// assert_eq!(4356f16.next_up(), 4360.0);
664 /// # }
665 /// ```
666 ///
667 /// This operation corresponds to IEEE-754 `nextUp`.
668 ///
669 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
670 /// [`INFINITY`]: Self::INFINITY
671 /// [`MIN`]: Self::MIN
672 /// [`MAX`]: Self::MAX
673 #[inline]
674 #[doc(alias = "nextUp")]
675 #[unstable(feature = "f16", issue = "116909")]
676 #[must_use = "method returns a new number and does not mutate the original value"]
677 pub const fn next_up(self) -> Self {
678 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
679 // denormals to zero. This is in general unsound and unsupported, but here
680 // we do our best to still produce the correct result on such targets.
681 let bits = self.to_bits();
682 if self.is_nan() || bits == Self::INFINITY.to_bits() {
683 return self;
684 }
685
686 let abs = bits & !Self::SIGN_MASK;
687 let next_bits = if abs == 0 {
688 Self::TINY_BITS
689 } else if bits == abs {
690 bits + 1
691 } else {
692 bits - 1
693 };
694 Self::from_bits(next_bits)
695 }
696
697 /// Returns the greatest number less than `self`.
698 ///
699 /// Let `TINY` be the smallest representable positive `f16`. Then,
700 /// - if `self.is_nan()`, this returns `self`;
701 /// - if `self` is [`INFINITY`], this returns [`MAX`];
702 /// - if `self` is `TINY`, this returns 0.0;
703 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
704 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
705 /// - otherwise the unique greatest value less than `self` is returned.
706 ///
707 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
708 /// is finite `x == x.next_down().next_up()` also holds.
709 ///
710 /// ```rust
711 /// #![feature(f16)]
712 /// # #[cfg(target_has_reliable_f16)] {
713 ///
714 /// let x = 1.0f16;
715 /// // Clamp value into range [0, 1).
716 /// let clamped = x.clamp(0.0, 1.0f16.next_down());
717 /// assert!(clamped < 1.0);
718 /// assert_eq!(clamped.next_up(), 1.0);
719 /// # }
720 /// ```
721 ///
722 /// This operation corresponds to IEEE-754 `nextDown`.
723 ///
724 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
725 /// [`INFINITY`]: Self::INFINITY
726 /// [`MIN`]: Self::MIN
727 /// [`MAX`]: Self::MAX
728 #[inline]
729 #[doc(alias = "nextDown")]
730 #[unstable(feature = "f16", issue = "116909")]
731 #[must_use = "method returns a new number and does not mutate the original value"]
732 pub const fn next_down(self) -> Self {
733 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
734 // denormals to zero. This is in general unsound and unsupported, but here
735 // we do our best to still produce the correct result on such targets.
736 let bits = self.to_bits();
737 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
738 return self;
739 }
740
741 let abs = bits & !Self::SIGN_MASK;
742 let next_bits = if abs == 0 {
743 Self::NEG_TINY_BITS
744 } else if bits == abs {
745 bits - 1
746 } else {
747 bits + 1
748 };
749 Self::from_bits(next_bits)
750 }
751
752 /// Takes the reciprocal (inverse) of a number, `1/x`.
753 ///
754 /// ```
755 /// #![feature(f16)]
756 /// # #[cfg(target_has_reliable_f16)] {
757 ///
758 /// let x = 2.0_f16;
759 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
760 ///
761 /// assert!(abs_difference <= f16::EPSILON);
762 /// # }
763 /// ```
764 #[inline]
765 #[unstable(feature = "f16", issue = "116909")]
766 #[must_use = "this returns the result of the operation, without modifying the original"]
767 pub const fn recip(self) -> Self {
768 1.0 / self
769 }
770
771 /// Converts radians to degrees.
772 ///
773 /// # Unspecified precision
774 ///
775 /// The precision of this function is non-deterministic. This means it varies by platform,
776 /// Rust version, and can even differ within the same execution from one invocation to the next.
777 ///
778 /// # Examples
779 ///
780 /// ```
781 /// #![feature(f16)]
782 /// # #[cfg(target_has_reliable_f16)] {
783 ///
784 /// let angle = std::f16::consts::PI;
785 ///
786 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
787 /// assert!(abs_difference <= 0.5);
788 /// # }
789 /// ```
790 #[inline]
791 #[unstable(feature = "f16", issue = "116909")]
792 #[must_use = "this returns the result of the operation, without modifying the original"]
793 pub const fn to_degrees(self) -> Self {
794 // Use a literal to avoid double rounding, consts::PI is already rounded,
795 // and dividing would round again.
796 const PIS_IN_180: f16 = 57.2957795130823208767981548141051703_f16;
797 self * PIS_IN_180
798 }
799
800 /// Converts degrees to radians.
801 ///
802 /// # Unspecified precision
803 ///
804 /// The precision of this function is non-deterministic. This means it varies by platform,
805 /// Rust version, and can even differ within the same execution from one invocation to the next.
806 ///
807 /// # Examples
808 ///
809 /// ```
810 /// #![feature(f16)]
811 /// # #[cfg(target_has_reliable_f16)] {
812 ///
813 /// let angle = 180.0f16;
814 ///
815 /// let abs_difference = (angle.to_radians() - std::f16::consts::PI).abs();
816 ///
817 /// assert!(abs_difference <= 0.01);
818 /// # }
819 /// ```
820 #[inline]
821 #[unstable(feature = "f16", issue = "116909")]
822 #[must_use = "this returns the result of the operation, without modifying the original"]
823 pub const fn to_radians(self) -> f16 {
824 // Use a literal to avoid double rounding, consts::PI is already rounded,
825 // and dividing would round again.
826 const RADS_PER_DEG: f16 = 0.017453292519943295769236907684886_f16;
827 self * RADS_PER_DEG
828 }
829
830 /// Returns the maximum of the two numbers, ignoring NaN.
831 ///
832 /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
833 /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
834 /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
835 /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
836 /// non-deterministically.
837 ///
838 /// The handling of NaNs follows the IEEE 754-2019 semantics for `maximumNumber`, treating all
839 /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
840 /// follows the IEEE 754-2008 semantics for `maxNum`.
841 ///
842 /// ```
843 /// #![feature(f16)]
844 /// # #[cfg(target_has_reliable_f16)] {
845 ///
846 /// let x = 1.0f16;
847 /// let y = 2.0f16;
848 ///
849 /// assert_eq!(x.max(y), y);
850 /// assert_eq!(x.max(f16::NAN), x);
851 /// # }
852 /// ```
853 #[inline]
854 #[unstable(feature = "f16", issue = "116909")]
855 #[rustc_const_unstable(feature = "f16", issue = "116909")]
856 #[must_use = "this returns the result of the comparison, without modifying either input"]
857 pub const fn max(self, other: f16) -> f16 {
858 intrinsics::maximum_number_nsz_f16(self, other)
859 }
860
861 /// Returns the minimum of the two numbers, ignoring NaN.
862 ///
863 /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
864 /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
865 /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
866 /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
867 /// non-deterministically.
868 ///
869 /// The handling of NaNs follows the IEEE 754-2019 semantics for `minimumNumber`, treating all
870 /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
871 /// follows the IEEE 754-2008 semantics for `minNum`.
872 ///
873 /// ```
874 /// #![feature(f16)]
875 /// # #[cfg(target_has_reliable_f16)] {
876 ///
877 /// let x = 1.0f16;
878 /// let y = 2.0f16;
879 ///
880 /// assert_eq!(x.min(y), x);
881 /// assert_eq!(x.min(f16::NAN), x);
882 /// # }
883 /// ```
884 #[inline]
885 #[unstable(feature = "f16", issue = "116909")]
886 #[rustc_const_unstable(feature = "f16", issue = "116909")]
887 #[must_use = "this returns the result of the comparison, without modifying either input"]
888 pub const fn min(self, other: f16) -> f16 {
889 intrinsics::minimum_number_nsz_f16(self, other)
890 }
891
892 /// Returns the maximum of the two numbers, propagating NaN.
893 ///
894 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
895 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
896 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
897 /// non-NaN inputs.
898 ///
899 /// This is in contrast to [`f16::max`] which only returns NaN when *both* arguments are NaN,
900 /// and which does not reliably order `-0.0` and `+0.0`.
901 ///
902 /// This follows the IEEE 754-2019 semantics for `maximum`.
903 ///
904 /// ```
905 /// #![feature(f16)]
906 /// #![feature(float_minimum_maximum)]
907 /// # #[cfg(target_has_reliable_f16)] {
908 ///
909 /// let x = 1.0f16;
910 /// let y = 2.0f16;
911 ///
912 /// assert_eq!(x.maximum(y), y);
913 /// assert!(x.maximum(f16::NAN).is_nan());
914 /// # }
915 /// ```
916 #[inline]
917 #[unstable(feature = "f16", issue = "116909")]
918 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
919 #[must_use = "this returns the result of the comparison, without modifying either input"]
920 pub const fn maximum(self, other: f16) -> f16 {
921 intrinsics::maximumf16(self, other)
922 }
923
924 /// Returns the minimum of the two numbers, propagating NaN.
925 ///
926 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
927 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
928 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
929 /// non-NaN inputs.
930 ///
931 /// This is in contrast to [`f16::min`] which only returns NaN when *both* arguments are NaN,
932 /// and which does not reliably order `-0.0` and `+0.0`.
933 ///
934 /// This follows the IEEE 754-2019 semantics for `minimum`.
935 ///
936 /// ```
937 /// #![feature(f16)]
938 /// #![feature(float_minimum_maximum)]
939 /// # #[cfg(target_has_reliable_f16)] {
940 ///
941 /// let x = 1.0f16;
942 /// let y = 2.0f16;
943 ///
944 /// assert_eq!(x.minimum(y), x);
945 /// assert!(x.minimum(f16::NAN).is_nan());
946 /// # }
947 /// ```
948 #[inline]
949 #[unstable(feature = "f16", issue = "116909")]
950 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
951 #[must_use = "this returns the result of the comparison, without modifying either input"]
952 pub const fn minimum(self, other: f16) -> f16 {
953 intrinsics::minimumf16(self, other)
954 }
955
956 /// Calculates the midpoint (average) between `self` and `rhs`.
957 ///
958 /// This returns NaN when *either* argument is NaN or if a combination of
959 /// +inf and -inf is provided as arguments.
960 ///
961 /// # Examples
962 ///
963 /// ```
964 /// #![feature(f16)]
965 /// # #[cfg(target_has_reliable_f16)] {
966 ///
967 /// assert_eq!(1f16.midpoint(4.0), 2.5);
968 /// assert_eq!((-5.5f16).midpoint(8.0), 1.25);
969 /// # }
970 /// ```
971 #[inline]
972 #[doc(alias = "average")]
973 #[unstable(feature = "f16", issue = "116909")]
974 #[rustc_const_unstable(feature = "f16", issue = "116909")]
975 #[must_use = "this returns the result of the operation, \
976 without modifying the original"]
977 pub const fn midpoint(self, other: f16) -> f16 {
978 const HI: f16 = f16::MAX * 0.5;
979
980 let (a, b) = (self, other);
981 let abs_a = a.abs();
982 let abs_b = b.abs();
983
984 if abs_a <= HI && abs_b <= HI {
985 // Overflow is impossible
986 (a + b) * 0.5
987 } else {
988 (a * 0.5) + (b * 0.5)
989 }
990 }
991
992 /// Rounds toward zero and converts to any primitive integer type,
993 /// assuming that the value is finite and fits in that type.
994 ///
995 /// ```
996 /// #![feature(f16)]
997 /// # #[cfg(target_has_reliable_f16)] {
998 ///
999 /// let value = 4.6_f16;
1000 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1001 /// assert_eq!(rounded, 4);
1002 ///
1003 /// let value = -128.9_f16;
1004 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1005 /// assert_eq!(rounded, i8::MIN);
1006 /// # }
1007 /// ```
1008 ///
1009 /// # Safety
1010 ///
1011 /// The value must:
1012 ///
1013 /// * Not be `NaN`
1014 /// * Not be infinite
1015 /// * Be representable in the return type `Int`, after truncating off its fractional part
1016 #[inline]
1017 #[unstable(feature = "f16", issue = "116909")]
1018 #[must_use = "this returns the result of the operation, without modifying the original"]
1019 pub unsafe fn to_int_unchecked<Int>(self) -> Int
1020 where
1021 Self: FloatToInt<Int>,
1022 {
1023 // SAFETY: the caller must uphold the safety contract for
1024 // `FloatToInt::to_int_unchecked`.
1025 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1026 }
1027
1028 /// Converts to the target float type, rounding as defined in IEEE 754.
1029 ///
1030 /// This is equivalent to `self as Flt`. Narrowing to a smaller type can
1031 /// produce an infinity.
1032 ///
1033 /// ```
1034 /// #![feature(float_conversions, f16)]
1035 /// # #[cfg(target_has_reliable_f16)] {
1036 ///
1037 /// let x = 1.5_f16;
1038 /// assert_eq!(x.cast::<f32>(), 1.5_f32);
1039 /// # }
1040 /// ```
1041 #[unstable(feature = "float_conversions", issue = "159913")]
1042 #[must_use = "this returns the result of the operation, without modifying the original"]
1043 #[inline]
1044 pub fn cast<Flt>(self) -> Flt
1045 where
1046 Self: FloatToFloat<Flt>,
1047 {
1048 FloatToFloat::<Flt>::cast(self)
1049 }
1050
1051 /// Rounds toward zero and converts to any primitive integer type, saturating
1052 /// at the type's boundaries and mapping `NaN` to zero.
1053 ///
1054 /// This is equivalent to `self as Int`.
1055 ///
1056 /// ```
1057 /// #![feature(float_conversions, f16)]
1058 /// # #[cfg(target_has_reliable_f16)] {
1059 ///
1060 /// assert_eq!(4.6_f16.to_int_saturating::<u8>(), 4);
1061 /// assert_eq!(f16::NAN.to_int_saturating::<u8>(), 0);
1062 /// # }
1063 /// ```
1064 #[unstable(feature = "float_conversions", issue = "159913")]
1065 #[must_use = "this returns the result of the operation, without modifying the original"]
1066 #[inline]
1067 pub fn to_int_saturating<Int>(self) -> Int
1068 where
1069 Self: FloatToInt<Int>,
1070 {
1071 FloatToInt::<Int>::to_int_saturating(self)
1072 }
1073
1074 /// Rounds toward zero and converts to any primitive integer type, returning
1075 /// `None` if the value is `NaN`, infinite, or does not fit in the target type.
1076 ///
1077 /// ```
1078 /// #![feature(float_conversions, f16)]
1079 /// # #[cfg(target_has_reliable_f16)] {
1080 ///
1081 /// assert_eq!(4.6_f16.to_int_checked::<u8>(), Some(4));
1082 /// assert_eq!(f16::NAN.to_int_checked::<u8>(), None);
1083 /// # }
1084 /// ```
1085 #[unstable(feature = "float_conversions", issue = "159913")]
1086 #[must_use = "this returns the result of the operation, without modifying the original"]
1087 #[inline]
1088 pub fn to_int_checked<Int>(self) -> Option<Int>
1089 where
1090 Self: FloatToInt<Int>,
1091 {
1092 FloatToInt::<Int>::to_int_checked(self)
1093 }
1094
1095 /// Rounds toward zero and converts to any primitive integer type.
1096 ///
1097 /// This is equivalent to `self.to_int_checked().unwrap()`.
1098 ///
1099 /// # Panics
1100 ///
1101 /// Panics if the value is `NaN`, infinite, or does not fit in the target type.
1102 ///
1103 /// ```
1104 /// #![feature(float_conversions, f16)]
1105 /// # #[cfg(target_has_reliable_f16)] {
1106 ///
1107 /// assert_eq!(4.6_f16.to_int_strict::<u8>(), 4);
1108 /// # }
1109 /// ```
1110 #[unstable(feature = "float_conversions", issue = "159913")]
1111 #[must_use = "this returns the result of the operation, without modifying the original"]
1112 #[inline]
1113 #[track_caller]
1114 pub fn to_int_strict<Int>(self) -> Int
1115 where
1116 Self: FloatToInt<Int>,
1117 {
1118 self.to_int_checked::<Int>()
1119 .expect("the value cannot be represented in the target integer type")
1120 }
1121
1122 /// Raw transmutation to `u16`.
1123 ///
1124 /// This is currently identical to `transmute::<f16, u16>(self)` on all platforms.
1125 ///
1126 /// See [`from_bits`](#method.from_bits) for some discussion of the
1127 /// portability of this operation (there are almost no issues).
1128 ///
1129 /// Note that this function is distinct from `as` casting, which attempts to
1130 /// preserve the *numeric* value, and not the bitwise value.
1131 ///
1132 /// ```
1133 /// #![feature(f16)]
1134 /// # #[cfg(target_has_reliable_f16)] {
1135 ///
1136 /// assert_ne!((1f16).to_bits(), 1f16 as u16); // to_bits() is not casting!
1137 /// assert_eq!((12.5f16).to_bits(), 0x4a40);
1138 /// # }
1139 /// ```
1140 #[inline]
1141 #[unstable(feature = "f16", issue = "116909")]
1142 #[must_use = "this returns the result of the operation, without modifying the original"]
1143 #[allow(unnecessary_transmutes)]
1144 pub const fn to_bits(self) -> u16 {
1145 // SAFETY: `u16` is a plain old datatype so we can always transmute to it.
1146 unsafe { mem::transmute(self) }
1147 }
1148
1149 /// Raw transmutation from `u16`.
1150 ///
1151 /// This is currently identical to `transmute::<u16, f16>(v)` on all platforms.
1152 /// It turns out this is incredibly portable, for two reasons:
1153 ///
1154 /// * Floats and Ints have the same endianness on all supported platforms.
1155 /// * IEEE 754 very precisely specifies the bit layout of floats.
1156 ///
1157 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1158 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1159 /// (notably x86 and ARM) picked the interpretation that was ultimately
1160 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1161 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1162 ///
1163 /// Rather than trying to preserve signaling-ness cross-platform, this
1164 /// implementation favors preserving the exact bits. This means that
1165 /// any payloads encoded in NaNs will be preserved even if the result of
1166 /// this method is sent over the network from an x86 machine to a MIPS one.
1167 ///
1168 /// If the results of this method are only manipulated by the same
1169 /// architecture that produced them, then there is no portability concern.
1170 ///
1171 /// If the input isn't NaN, then there is no portability concern.
1172 ///
1173 /// If you don't care about signalingness (very likely), then there is no
1174 /// portability concern.
1175 ///
1176 /// Note that this function is distinct from `as` casting, which attempts to
1177 /// preserve the *numeric* value, and not the bitwise value.
1178 ///
1179 /// ```
1180 /// #![feature(f16)]
1181 /// # #[cfg(target_has_reliable_f16)] {
1182 ///
1183 /// let v = f16::from_bits(0x4a40);
1184 /// assert_eq!(v, 12.5);
1185 /// # }
1186 /// ```
1187 #[inline]
1188 #[must_use]
1189 #[unstable(feature = "f16", issue = "116909")]
1190 #[allow(unnecessary_transmutes)]
1191 pub const fn from_bits(v: u16) -> Self {
1192 // It turns out the safety issues with sNaN were overblown! Hooray!
1193 // SAFETY: `u16` is a plain old datatype so we can always transmute from it.
1194 unsafe { mem::transmute(v) }
1195 }
1196
1197 /// Returns the memory representation of this floating point number as a byte array in
1198 /// big-endian (network) byte order.
1199 ///
1200 /// See [`from_bits`](Self::from_bits) for some discussion of the
1201 /// portability of this operation (there are almost no issues).
1202 ///
1203 /// # Examples
1204 ///
1205 /// ```
1206 /// #![feature(f16)]
1207 /// # #[cfg(target_has_reliable_f16)] {
1208 ///
1209 /// let bytes = 12.5f16.to_be_bytes();
1210 /// assert_eq!(bytes, [0x4a, 0x40]);
1211 /// # }
1212 /// ```
1213 #[inline]
1214 #[unstable(feature = "f16", issue = "116909")]
1215 #[must_use = "this returns the result of the operation, without modifying the original"]
1216 pub const fn to_be_bytes(self) -> [u8; 2] {
1217 self.to_bits().to_be_bytes()
1218 }
1219
1220 /// Returns the memory representation of this floating point number as a byte array in
1221 /// little-endian byte order.
1222 ///
1223 /// See [`from_bits`](Self::from_bits) for some discussion of the
1224 /// portability of this operation (there are almost no issues).
1225 ///
1226 /// # Examples
1227 ///
1228 /// ```
1229 /// #![feature(f16)]
1230 /// # #[cfg(target_has_reliable_f16)] {
1231 ///
1232 /// let bytes = 12.5f16.to_le_bytes();
1233 /// assert_eq!(bytes, [0x40, 0x4a]);
1234 /// # }
1235 /// ```
1236 #[inline]
1237 #[unstable(feature = "f16", issue = "116909")]
1238 #[must_use = "this returns the result of the operation, without modifying the original"]
1239 pub const fn to_le_bytes(self) -> [u8; 2] {
1240 self.to_bits().to_le_bytes()
1241 }
1242
1243 /// Returns the memory representation of this floating point number as a byte array in
1244 /// native byte order.
1245 ///
1246 /// As the target platform's native endianness is used, portable code
1247 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1248 ///
1249 /// [`to_be_bytes`]: f16::to_be_bytes
1250 /// [`to_le_bytes`]: f16::to_le_bytes
1251 ///
1252 /// See [`from_bits`](Self::from_bits) for some discussion of the
1253 /// portability of this operation (there are almost no issues).
1254 ///
1255 /// # Examples
1256 ///
1257 /// ```
1258 /// #![feature(f16)]
1259 /// # #[cfg(target_has_reliable_f16)] {
1260 ///
1261 /// let bytes = 12.5f16.to_ne_bytes();
1262 /// assert_eq!(
1263 /// bytes,
1264 /// if cfg!(target_endian = "big") {
1265 /// [0x4a, 0x40]
1266 /// } else {
1267 /// [0x40, 0x4a]
1268 /// }
1269 /// );
1270 /// # }
1271 /// ```
1272 #[inline]
1273 #[unstable(feature = "f16", issue = "116909")]
1274 #[must_use = "this returns the result of the operation, without modifying the original"]
1275 pub const fn to_ne_bytes(self) -> [u8; 2] {
1276 self.to_bits().to_ne_bytes()
1277 }
1278
1279 /// Creates a floating point value from its representation as a byte array in big endian.
1280 ///
1281 /// See [`from_bits`](Self::from_bits) for some discussion of the
1282 /// portability of this operation (there are almost no issues).
1283 ///
1284 /// # Examples
1285 ///
1286 /// ```
1287 /// #![feature(f16)]
1288 /// # #[cfg(target_has_reliable_f16)] {
1289 ///
1290 /// let value = f16::from_be_bytes([0x4a, 0x40]);
1291 /// assert_eq!(value, 12.5);
1292 /// # }
1293 /// ```
1294 #[inline]
1295 #[must_use]
1296 #[unstable(feature = "f16", issue = "116909")]
1297 pub const fn from_be_bytes(bytes: [u8; 2]) -> Self {
1298 Self::from_bits(u16::from_be_bytes(bytes))
1299 }
1300
1301 /// Creates a floating point value from its representation as a byte array in little endian.
1302 ///
1303 /// See [`from_bits`](Self::from_bits) for some discussion of the
1304 /// portability of this operation (there are almost no issues).
1305 ///
1306 /// # Examples
1307 ///
1308 /// ```
1309 /// #![feature(f16)]
1310 /// # #[cfg(target_has_reliable_f16)] {
1311 ///
1312 /// let value = f16::from_le_bytes([0x40, 0x4a]);
1313 /// assert_eq!(value, 12.5);
1314 /// # }
1315 /// ```
1316 #[inline]
1317 #[must_use]
1318 #[unstable(feature = "f16", issue = "116909")]
1319 pub const fn from_le_bytes(bytes: [u8; 2]) -> Self {
1320 Self::from_bits(u16::from_le_bytes(bytes))
1321 }
1322
1323 /// Creates a floating point value from its representation as a byte array in native endian.
1324 ///
1325 /// As the target platform's native endianness is used, portable code
1326 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1327 /// appropriate instead.
1328 ///
1329 /// [`from_be_bytes`]: f16::from_be_bytes
1330 /// [`from_le_bytes`]: f16::from_le_bytes
1331 ///
1332 /// See [`from_bits`](Self::from_bits) for some discussion of the
1333 /// portability of this operation (there are almost no issues).
1334 ///
1335 /// # Examples
1336 ///
1337 /// ```
1338 /// #![feature(f16)]
1339 /// # #[cfg(target_has_reliable_f16)] {
1340 ///
1341 /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") {
1342 /// [0x4a, 0x40]
1343 /// } else {
1344 /// [0x40, 0x4a]
1345 /// });
1346 /// assert_eq!(value, 12.5);
1347 /// # }
1348 /// ```
1349 #[inline]
1350 #[must_use]
1351 #[unstable(feature = "f16", issue = "116909")]
1352 pub const fn from_ne_bytes(bytes: [u8; 2]) -> Self {
1353 Self::from_bits(u16::from_ne_bytes(bytes))
1354 }
1355
1356 /// Returns the ordering between `self` and `other`.
1357 ///
1358 /// Unlike the standard partial comparison between floating point numbers,
1359 /// this comparison always produces an ordering in accordance to
1360 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1361 /// floating point standard. The values are ordered in the following sequence:
1362 ///
1363 /// - negative quiet NaN
1364 /// - negative signaling NaN
1365 /// - negative infinity
1366 /// - negative numbers
1367 /// - negative subnormal numbers
1368 /// - negative zero
1369 /// - positive zero
1370 /// - positive subnormal numbers
1371 /// - positive numbers
1372 /// - positive infinity
1373 /// - positive signaling NaN
1374 /// - positive quiet NaN.
1375 ///
1376 /// The ordering established by this function does not always agree with the
1377 /// [`PartialOrd`] and [`PartialEq`] implementations of `f16`. For example,
1378 /// they consider negative and positive zero equal, while `total_cmp`
1379 /// doesn't.
1380 ///
1381 /// The interpretation of the signaling NaN bit follows the definition in
1382 /// the IEEE 754 standard, which may not match the interpretation by some of
1383 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1384 ///
1385 /// # Example
1386 ///
1387 /// ```
1388 /// #![feature(f16)]
1389 /// # #[cfg(target_has_reliable_f16)] {
1390 ///
1391 /// struct GoodBoy {
1392 /// name: &'static str,
1393 /// weight: f16,
1394 /// }
1395 ///
1396 /// let mut bois = vec![
1397 /// GoodBoy { name: "Pucci", weight: 0.1 },
1398 /// GoodBoy { name: "Woofer", weight: 99.0 },
1399 /// GoodBoy { name: "Yapper", weight: 10.0 },
1400 /// GoodBoy { name: "Chonk", weight: f16::INFINITY },
1401 /// GoodBoy { name: "Abs. Unit", weight: f16::NAN },
1402 /// GoodBoy { name: "Floaty", weight: -5.0 },
1403 /// ];
1404 ///
1405 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1406 ///
1407 /// // `f16::NAN` could be positive or negative, which will affect the sort order.
1408 /// if f16::NAN.is_sign_negative() {
1409 /// bois.into_iter().map(|b| b.weight)
1410 /// .zip([f16::NAN, -5.0, 0.1, 10.0, 99.0, f16::INFINITY].iter())
1411 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1412 /// } else {
1413 /// bois.into_iter().map(|b| b.weight)
1414 /// .zip([-5.0, 0.1, 10.0, 99.0, f16::INFINITY, f16::NAN].iter())
1415 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1416 /// }
1417 /// # }
1418 /// ```
1419 #[inline]
1420 #[must_use]
1421 #[unstable(feature = "f16", issue = "116909")]
1422 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1423 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1424 let mut left = self.to_bits() as i16;
1425 let mut right = other.to_bits() as i16;
1426
1427 // In case of negatives, flip all the bits except the sign
1428 // to achieve a similar layout as two's complement integers
1429 //
1430 // Why does this work? IEEE 754 floats consist of three fields:
1431 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1432 // fields as a whole have the property that their bitwise order is
1433 // equal to the numeric magnitude where the magnitude is defined.
1434 // The magnitude is not normally defined on NaN values, but
1435 // IEEE 754 totalOrder defines the NaN values also to follow the
1436 // bitwise order. This leads to order explained in the doc comment.
1437 // However, the representation of magnitude is the same for negative
1438 // and positive numbers – only the sign bit is different.
1439 // To easily compare the floats as signed integers, we need to
1440 // flip the exponent and mantissa bits in case of negative numbers.
1441 // We effectively convert the numbers to "two's complement" form.
1442 //
1443 // To do the flipping, we construct a mask and XOR against it.
1444 // We branchlessly calculate an "all-ones except for the sign bit"
1445 // mask from negative-signed values: right shifting sign-extends
1446 // the integer, so we "fill" the mask with sign bits, and then
1447 // convert to unsigned to push one more zero bit.
1448 // On positive values, the mask is all zeros, so it's a no-op.
1449 left ^= (((left >> 15) as u16) >> 1) as i16;
1450 right ^= (((right >> 15) as u16) >> 1) as i16;
1451
1452 left.cmp(&right)
1453 }
1454
1455 /// Restrict a value to a certain interval unless it is NaN.
1456 ///
1457 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1458 /// less than `min`. Otherwise this returns `self`.
1459 ///
1460 /// Note that this function returns NaN if the initial value was NaN as
1461 /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1462 /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1463 ///
1464 /// # Panics
1465 ///
1466 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1467 ///
1468 /// # Examples
1469 ///
1470 /// ```
1471 /// #![feature(f16)]
1472 /// # #[cfg(target_has_reliable_f16)] {
1473 ///
1474 /// assert!((-3.0f16).clamp(-2.0, 1.0) == -2.0);
1475 /// assert!((0.0f16).clamp(-2.0, 1.0) == 0.0);
1476 /// assert!((2.0f16).clamp(-2.0, 1.0) == 1.0);
1477 /// assert!((f16::NAN).clamp(-2.0, 1.0).is_nan());
1478 ///
1479 /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1480 /// assert!((0.0f16).clamp(-0.0, -0.0) == 0.0);
1481 /// assert!((1.0f16).clamp(-0.0, 0.0) == 0.0);
1482 /// // This is definitely a negative zero.
1483 /// assert!((-1.0f16).clamp(-0.0, 1.0).is_sign_negative());
1484 /// # }
1485 /// ```
1486 #[inline]
1487 #[unstable(feature = "f16", issue = "116909")]
1488 #[must_use = "method returns a new number and does not mutate the original value"]
1489 #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1490 pub const fn clamp(mut self, min: f16, max: f16) -> f16 {
1491 const_assert!(
1492 min <= max,
1493 "min > max, or either was NaN",
1494 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1495 min: f16,
1496 max: f16,
1497 );
1498
1499 if self < min {
1500 self = min;
1501 }
1502 if self > max {
1503 self = max;
1504 }
1505 self
1506 }
1507
1508 /// Clamps this number to a symmetric range centered around zero.
1509 ///
1510 /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1511 ///
1512 /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1513 /// explicit about the intent.
1514 ///
1515 /// # Panics
1516 ///
1517 /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1518 ///
1519 /// # Examples
1520 ///
1521 /// ```
1522 /// #![feature(f16)]
1523 /// #![feature(clamp_magnitude)]
1524 /// # #[cfg(target_has_reliable_f16)] {
1525 /// assert_eq!(5.0f16.clamp_magnitude(3.0), 3.0);
1526 /// assert_eq!((-5.0f16).clamp_magnitude(3.0), -3.0);
1527 /// assert_eq!(2.0f16.clamp_magnitude(3.0), 2.0);
1528 /// assert_eq!((-2.0f16).clamp_magnitude(3.0), -2.0);
1529 /// # }
1530 /// ```
1531 #[inline]
1532 #[unstable(feature = "clamp_magnitude", issue = "148519")]
1533 #[must_use = "this returns the clamped value and does not modify the original"]
1534 #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1535 pub fn clamp_magnitude(self, limit: f16) -> f16 {
1536 assert!(limit >= 0.0, "limit must be non-negative and not NaN");
1537 let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1538 self.clamp(-limit, limit)
1539 }
1540
1541 /// Computes the absolute value of `self`.
1542 ///
1543 /// This function always returns the precise result.
1544 ///
1545 /// # Examples
1546 ///
1547 /// ```
1548 /// #![feature(f16)]
1549 /// # #[cfg(target_has_reliable_f16)] {
1550 ///
1551 /// let x = 3.5_f16;
1552 /// let y = -3.5_f16;
1553 ///
1554 /// assert_eq!(x.abs(), x);
1555 /// assert_eq!(y.abs(), -y);
1556 ///
1557 /// assert!(f16::NAN.abs().is_nan());
1558 /// # }
1559 /// ```
1560 #[inline]
1561 #[unstable(feature = "f16", issue = "116909")]
1562 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1563 #[must_use = "method returns a new number and does not mutate the original value"]
1564 pub const fn abs(self) -> Self {
1565 intrinsics::fabs(self)
1566 }
1567
1568 /// Returns a number that represents the sign of `self`.
1569 ///
1570 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1571 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1572 /// - NaN if the number is NaN
1573 ///
1574 /// # Examples
1575 ///
1576 /// ```
1577 /// #![feature(f16)]
1578 /// # #[cfg(target_has_reliable_f16)] {
1579 ///
1580 /// let f = 3.5_f16;
1581 ///
1582 /// assert_eq!(f.signum(), 1.0);
1583 /// assert_eq!(f16::NEG_INFINITY.signum(), -1.0);
1584 ///
1585 /// assert!(f16::NAN.signum().is_nan());
1586 /// # }
1587 /// ```
1588 #[inline]
1589 #[unstable(feature = "f16", issue = "116909")]
1590 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1591 #[must_use = "method returns a new number and does not mutate the original value"]
1592 pub const fn signum(self) -> f16 {
1593 if self.is_nan() { Self::NAN } else { 1.0_f16.copysign(self) }
1594 }
1595
1596 /// Returns a number composed of the magnitude of `self` and the sign of
1597 /// `sign`.
1598 ///
1599 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1600 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1601 /// returned.
1602 ///
1603 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1604 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1605 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1606 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1607 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1608 /// info.
1609 ///
1610 /// # Examples
1611 ///
1612 /// ```
1613 /// #![feature(f16)]
1614 /// # #[cfg(target_has_reliable_f16)] {
1615 ///
1616 /// let f = 3.5_f16;
1617 ///
1618 /// assert_eq!(f.copysign(0.42), 3.5_f16);
1619 /// assert_eq!(f.copysign(-0.42), -3.5_f16);
1620 /// assert_eq!((-f).copysign(0.42), 3.5_f16);
1621 /// assert_eq!((-f).copysign(-0.42), -3.5_f16);
1622 ///
1623 /// assert!(f16::NAN.copysign(1.0).is_nan());
1624 /// # }
1625 /// ```
1626 #[inline]
1627 #[unstable(feature = "f16", issue = "116909")]
1628 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1629 #[must_use = "method returns a new number and does not mutate the original value"]
1630 pub const fn copysign(self, sign: f16) -> f16 {
1631 intrinsics::copysignf16(self, sign)
1632 }
1633
1634 /// Float addition that allows optimizations based on algebraic rules.
1635 ///
1636 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1637 #[must_use = "method returns a new number and does not mutate the original value"]
1638 #[unstable(feature = "f16", issue = "116909")]
1639 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1640 #[inline]
1641 pub const fn algebraic_add(self, rhs: f16) -> f16 {
1642 intrinsics::fadd_algebraic(self, rhs)
1643 }
1644
1645 /// Float subtraction that allows optimizations based on algebraic rules.
1646 ///
1647 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1648 #[must_use = "method returns a new number and does not mutate the original value"]
1649 #[unstable(feature = "f16", issue = "116909")]
1650 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1651 #[inline]
1652 pub const fn algebraic_sub(self, rhs: f16) -> f16 {
1653 intrinsics::fsub_algebraic(self, rhs)
1654 }
1655
1656 /// Float multiplication that allows optimizations based on algebraic rules.
1657 ///
1658 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1659 #[must_use = "method returns a new number and does not mutate the original value"]
1660 #[unstable(feature = "f16", issue = "116909")]
1661 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1662 #[inline]
1663 pub const fn algebraic_mul(self, rhs: f16) -> f16 {
1664 intrinsics::fmul_algebraic(self, rhs)
1665 }
1666
1667 /// Float division that allows optimizations based on algebraic rules.
1668 ///
1669 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1670 #[must_use = "method returns a new number and does not mutate the original value"]
1671 #[unstable(feature = "f16", issue = "116909")]
1672 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1673 #[inline]
1674 pub const fn algebraic_div(self, rhs: f16) -> f16 {
1675 intrinsics::fdiv_algebraic(self, rhs)
1676 }
1677
1678 /// Float remainder that allows optimizations based on algebraic rules.
1679 ///
1680 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1681 #[must_use = "method returns a new number and does not mutate the original value"]
1682 #[unstable(feature = "f16", issue = "116909")]
1683 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1684 #[inline]
1685 pub const fn algebraic_rem(self, rhs: f16) -> f16 {
1686 intrinsics::frem_algebraic(self, rhs)
1687 }
1688
1689 /// Returns `self` if the value is not NaN, otherwise returns `replacement`
1690 /// if `self` is NaN.
1691 ///
1692 /// # Examples
1693 ///
1694 /// ```
1695 /// #![feature(f16)]
1696 /// #![feature(float_nan_to)]
1697 /// # #[cfg(target_has_reliable_f16)] {
1698 ///
1699 /// let n = f16::NAN;
1700 /// let x = 2.0f16;
1701 /// let y = f16::INFINITY;
1702 ///
1703 /// assert_eq!(n.nan_to(0.0f16), 0.0f16);
1704 /// assert_eq!(x.nan_to(0.0f16), 2.0f16);
1705 /// assert_eq!(y.nan_to(0.0f16), f16::INFINITY);
1706 /// # }
1707 /// ```
1708 #[must_use = "method returns a new float and does not mutate the original value"]
1709 #[unstable(feature = "float_nan_to", issue = "161248")]
1710 #[rustc_const_unstable(feature = "float_nan_to", issue = "161248")]
1711 #[inline]
1712 pub const fn nan_to(self, replacement: f16) -> f16 {
1713 if self.is_nan() { replacement } else { self }
1714 }
1715}
1716
1717// Functions in this module fall into `core_float_math`
1718// #[unstable(feature = "core_float_math", issue = "137578")]
1719#[cfg(not(test))]
1720#[doc(test(attr(
1721 feature(cfg_target_has_reliable_f16_f128),
1722 expect(internal_features),
1723 allow(unused_features)
1724)))]
1725impl f16 {
1726 /// Returns the largest integer less than or equal to `self`.
1727 ///
1728 /// This function always returns the precise result.
1729 ///
1730 /// # Examples
1731 ///
1732 /// ```
1733 /// #![feature(f16)]
1734 /// # #[cfg(target_has_reliable_f16)] {
1735 ///
1736 /// let f = 3.7_f16;
1737 /// let g = 3.0_f16;
1738 /// let h = -3.7_f16;
1739 ///
1740 /// assert_eq!(f.floor(), 3.0);
1741 /// assert_eq!(g.floor(), 3.0);
1742 /// assert_eq!(h.floor(), -4.0);
1743 /// # }
1744 /// ```
1745 #[inline]
1746 #[rustc_allow_incoherent_impl]
1747 #[unstable(feature = "f16", issue = "116909")]
1748 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1749 #[must_use = "method returns a new number and does not mutate the original value"]
1750 pub const fn floor(self) -> f16 {
1751 intrinsics::floorf16(self)
1752 }
1753
1754 /// Returns the smallest integer greater than or equal to `self`.
1755 ///
1756 /// This function always returns the precise result.
1757 ///
1758 /// # Examples
1759 ///
1760 /// ```
1761 /// #![feature(f16)]
1762 /// # #[cfg(target_has_reliable_f16)] {
1763 ///
1764 /// let f = 3.01_f16;
1765 /// let g = 4.0_f16;
1766 ///
1767 /// assert_eq!(f.ceil(), 4.0);
1768 /// assert_eq!(g.ceil(), 4.0);
1769 /// # }
1770 /// ```
1771 #[inline]
1772 #[doc(alias = "ceiling")]
1773 #[rustc_allow_incoherent_impl]
1774 #[unstable(feature = "f16", issue = "116909")]
1775 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1776 #[must_use = "method returns a new number and does not mutate the original value"]
1777 pub const fn ceil(self) -> f16 {
1778 intrinsics::ceilf16(self)
1779 }
1780
1781 /// Returns the nearest integer to `self`. If a value is half-way between two
1782 /// integers, round away from `0.0`.
1783 ///
1784 /// This function always returns the precise result.
1785 ///
1786 /// # Examples
1787 ///
1788 /// ```
1789 /// #![feature(f16)]
1790 /// # #[cfg(target_has_reliable_f16)] {
1791 ///
1792 /// let f = 3.3_f16;
1793 /// let g = -3.3_f16;
1794 /// let h = -3.7_f16;
1795 /// let i = 3.5_f16;
1796 /// let j = 4.5_f16;
1797 ///
1798 /// assert_eq!(f.round(), 3.0);
1799 /// assert_eq!(g.round(), -3.0);
1800 /// assert_eq!(h.round(), -4.0);
1801 /// assert_eq!(i.round(), 4.0);
1802 /// assert_eq!(j.round(), 5.0);
1803 /// # }
1804 /// ```
1805 #[inline]
1806 #[rustc_allow_incoherent_impl]
1807 #[unstable(feature = "f16", issue = "116909")]
1808 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1809 #[must_use = "method returns a new number and does not mutate the original value"]
1810 pub const fn round(self) -> f16 {
1811 intrinsics::roundf16(self)
1812 }
1813
1814 /// Returns the nearest integer to a number. Rounds half-way cases to the number
1815 /// with an even least significant digit.
1816 ///
1817 /// This function always returns the precise result.
1818 ///
1819 /// # Examples
1820 ///
1821 /// ```
1822 /// #![feature(f16)]
1823 /// # #[cfg(target_has_reliable_f16)] {
1824 ///
1825 /// let f = 3.3_f16;
1826 /// let g = -3.3_f16;
1827 /// let h = 3.5_f16;
1828 /// let i = 4.5_f16;
1829 ///
1830 /// assert_eq!(f.round_ties_even(), 3.0);
1831 /// assert_eq!(g.round_ties_even(), -3.0);
1832 /// assert_eq!(h.round_ties_even(), 4.0);
1833 /// assert_eq!(i.round_ties_even(), 4.0);
1834 /// # }
1835 /// ```
1836 #[inline]
1837 #[rustc_allow_incoherent_impl]
1838 #[unstable(feature = "f16", issue = "116909")]
1839 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1840 #[must_use = "method returns a new number and does not mutate the original value"]
1841 pub const fn round_ties_even(self) -> f16 {
1842 intrinsics::round_ties_even_f16(self)
1843 }
1844
1845 /// Returns the integer part of `self`.
1846 /// This means that non-integer numbers are always truncated towards zero.
1847 ///
1848 /// This function always returns the precise result.
1849 ///
1850 /// # Examples
1851 ///
1852 /// ```
1853 /// #![feature(f16)]
1854 /// # #[cfg(target_has_reliable_f16)] {
1855 ///
1856 /// let f = 3.7_f16;
1857 /// let g = 3.0_f16;
1858 /// let h = -3.7_f16;
1859 ///
1860 /// assert_eq!(f.trunc(), 3.0);
1861 /// assert_eq!(g.trunc(), 3.0);
1862 /// assert_eq!(h.trunc(), -3.0);
1863 /// # }
1864 /// ```
1865 #[inline]
1866 #[doc(alias = "truncate")]
1867 #[rustc_allow_incoherent_impl]
1868 #[unstable(feature = "f16", issue = "116909")]
1869 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1870 #[must_use = "method returns a new number and does not mutate the original value"]
1871 pub const fn trunc(self) -> f16 {
1872 intrinsics::truncf16(self)
1873 }
1874
1875 /// Returns the fractional part of `self`.
1876 ///
1877 /// This function always returns the precise result.
1878 ///
1879 /// # Examples
1880 ///
1881 /// ```
1882 /// #![feature(f16)]
1883 /// # #[cfg(target_has_reliable_f16)] {
1884 ///
1885 /// let x = 3.6_f16;
1886 /// let y = -3.6_f16;
1887 /// let abs_difference_x = (x.fract() - 0.6).abs();
1888 /// let abs_difference_y = (y.fract() - (-0.6)).abs();
1889 ///
1890 /// assert!(abs_difference_x <= f16::EPSILON);
1891 /// assert!(abs_difference_y <= f16::EPSILON);
1892 /// # }
1893 /// ```
1894 #[inline]
1895 #[rustc_allow_incoherent_impl]
1896 #[unstable(feature = "f16", issue = "116909")]
1897 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1898 #[must_use = "method returns a new number and does not mutate the original value"]
1899 pub const fn fract(self) -> f16 {
1900 self - self.trunc()
1901 }
1902
1903 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1904 /// error, yielding a more accurate result than an unfused multiply-add.
1905 ///
1906 /// Using `mul_add` *may* be more performant than an unfused multiply-add if
1907 /// the target architecture has a dedicated `fma` CPU instruction. However,
1908 /// this is not always true, and will be heavily dependant on designing
1909 /// algorithms with specific target hardware in mind.
1910 ///
1911 /// # Precision
1912 ///
1913 /// The result of this operation is guaranteed to be the rounded
1914 /// infinite-precision result. It is specified by IEEE 754 as
1915 /// `fusedMultiplyAdd` and guaranteed not to change.
1916 ///
1917 /// # Examples
1918 ///
1919 /// ```
1920 /// #![feature(f16)]
1921 /// # #[cfg(target_has_reliable_f16)] {
1922 ///
1923 /// let m = 10.0_f16;
1924 /// let x = 4.0_f16;
1925 /// let b = 60.0_f16;
1926 ///
1927 /// assert_eq!(m.mul_add(x, b), 100.0);
1928 /// assert_eq!(m * x + b, 100.0);
1929 ///
1930 /// let one_plus_eps = 1.0_f16 + f16::EPSILON;
1931 /// let one_minus_eps = 1.0_f16 - f16::EPSILON;
1932 /// let minus_one = -1.0_f16;
1933 ///
1934 /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1935 /// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f16::EPSILON * f16::EPSILON);
1936 /// // Different rounding with the non-fused multiply and add.
1937 /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1938 /// # }
1939 /// ```
1940 #[inline]
1941 #[rustc_allow_incoherent_impl]
1942 #[unstable(feature = "f16", issue = "116909")]
1943 #[doc(alias = "fmaf16", alias = "fusedMultiplyAdd")]
1944 #[must_use = "method returns a new number and does not mutate the original value"]
1945 pub const fn mul_add(self, a: f16, b: f16) -> f16 {
1946 intrinsics::fmaf16(self, a, b)
1947 }
1948
1949 /// Calculates Euclidean division, the matching method for `rem_euclid`.
1950 ///
1951 /// This computes the integer `n` such that
1952 /// `self = n * rhs + self.rem_euclid(rhs)`.
1953 /// In other words, the result is `self / rhs` rounded to the integer `n`
1954 /// such that `self >= n * rhs`.
1955 ///
1956 /// # Precision
1957 ///
1958 /// The result of this operation is guaranteed to be the rounded
1959 /// infinite-precision result.
1960 ///
1961 /// # Examples
1962 ///
1963 /// ```
1964 /// #![feature(f16)]
1965 /// # #[cfg(target_has_reliable_f16)] {
1966 ///
1967 /// let a: f16 = 7.0;
1968 /// let b = 4.0;
1969 /// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
1970 /// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
1971 /// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
1972 /// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
1973 /// # }
1974 /// ```
1975 #[inline]
1976 #[rustc_allow_incoherent_impl]
1977 #[unstable(feature = "f16", issue = "116909")]
1978 #[must_use = "method returns a new number and does not mutate the original value"]
1979 pub fn div_euclid(self, rhs: f16) -> f16 {
1980 let q = (self / rhs).trunc();
1981 if self % rhs < 0.0 {
1982 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1983 }
1984 q
1985 }
1986
1987 /// Calculates the least nonnegative remainder of `self` when
1988 /// divided by `rhs`.
1989 ///
1990 /// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
1991 /// most cases. However, due to a floating point round-off error it can
1992 /// result in `r == rhs.abs()`, violating the mathematical definition, if
1993 /// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
1994 /// This result is not an element of the function's codomain, but it is the
1995 /// closest floating point number in the real numbers and thus fulfills the
1996 /// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
1997 /// approximately.
1998 ///
1999 /// # Precision
2000 ///
2001 /// The result of this operation is guaranteed to be the rounded
2002 /// infinite-precision result.
2003 ///
2004 /// # Examples
2005 ///
2006 /// ```
2007 /// #![feature(f16)]
2008 /// # #[cfg(target_has_reliable_f16)] {
2009 ///
2010 /// let a: f16 = 7.0;
2011 /// let b = 4.0;
2012 /// assert_eq!(a.rem_euclid(b), 3.0);
2013 /// assert_eq!((-a).rem_euclid(b), 1.0);
2014 /// assert_eq!(a.rem_euclid(-b), 3.0);
2015 /// assert_eq!((-a).rem_euclid(-b), 1.0);
2016 /// // limitation due to round-off error
2017 /// assert!((-f16::EPSILON).rem_euclid(3.0) != 0.0);
2018 /// # }
2019 /// ```
2020 #[inline]
2021 #[rustc_allow_incoherent_impl]
2022 #[doc(alias = "modulo", alias = "mod")]
2023 #[unstable(feature = "f16", issue = "116909")]
2024 #[must_use = "method returns a new number and does not mutate the original value"]
2025 pub fn rem_euclid(self, rhs: f16) -> f16 {
2026 let r = self % rhs;
2027 if r < 0.0 { r + rhs.abs() } else { r }
2028 }
2029
2030 /// Raises a number to an integer power.
2031 ///
2032 /// Using this function is generally faster than using `powf`.
2033 /// It might have a different sequence of rounding operations than `powf`,
2034 /// so the results are not guaranteed to agree.
2035 ///
2036 /// Note that this function is special in that it can return non-NaN results for NaN inputs. For
2037 /// example, `f16::powi(f16::NAN, 0)` returns `1.0`. However, if an input is a *signaling*
2038 /// NaN, then the result is non-deterministically either a NaN or the result that the
2039 /// corresponding quiet NaN would produce.
2040 ///
2041 /// # Unspecified precision
2042 ///
2043 /// The precision of this function is non-deterministic. This means it varies by platform,
2044 /// Rust version, and can even differ within the same execution from one invocation to the next.
2045 ///
2046 /// # Examples
2047 ///
2048 /// ```
2049 /// #![feature(f16)]
2050 /// # #[cfg(target_has_reliable_f16_math)] {
2051 ///
2052 /// let x = 2.0_f16;
2053 /// let abs_difference = (x.powi(2) - (x * x)).abs();
2054 /// assert!(abs_difference <= 0.1);
2055 ///
2056 /// assert_eq!(f16::powi(f16::NAN, 0), 1.0);
2057 /// assert_eq!(f16::powi(0.0, 0), 1.0);
2058 /// # }
2059 /// ```
2060 #[inline]
2061 #[rustc_allow_incoherent_impl]
2062 #[unstable(feature = "f16", issue = "116909")]
2063 #[must_use = "method returns a new number and does not mutate the original value"]
2064 pub fn powi(self, n: i32) -> f16 {
2065 intrinsics::powif16(self, n)
2066 }
2067
2068 /// Returns the square root of a number.
2069 ///
2070 /// Returns NaN if `self` is a negative number other than `-0.0`.
2071 ///
2072 /// # Precision
2073 ///
2074 /// The result of this operation is guaranteed to be the rounded
2075 /// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
2076 /// and guaranteed not to change.
2077 ///
2078 /// # Examples
2079 ///
2080 /// ```
2081 /// #![feature(f16)]
2082 /// # #[cfg(target_has_reliable_f16)] {
2083 ///
2084 /// let positive = 4.0_f16;
2085 /// let negative = -4.0_f16;
2086 /// let negative_zero = -0.0_f16;
2087 ///
2088 /// assert_eq!(positive.sqrt(), 2.0);
2089 /// assert!(negative.sqrt().is_nan());
2090 /// assert!(negative_zero.sqrt() == negative_zero);
2091 /// # }
2092 /// ```
2093 #[inline]
2094 #[doc(alias = "squareRoot")]
2095 #[rustc_allow_incoherent_impl]
2096 #[unstable(feature = "f16", issue = "116909")]
2097 #[must_use = "method returns a new number and does not mutate the original value"]
2098 pub fn sqrt(self) -> f16 {
2099 intrinsics::sqrtf16(self)
2100 }
2101
2102 /// Returns the cube root of a number.
2103 ///
2104 /// # Unspecified precision
2105 ///
2106 /// The precision of this function is non-deterministic. This means it varies by platform,
2107 /// Rust version, and can even differ within the same execution from one invocation to the next.
2108 ///
2109 /// This function currently corresponds to the `cbrtf` from libc on Unix
2110 /// and Windows. Note that this might change in the future.
2111 ///
2112 /// # Examples
2113 ///
2114 /// ```
2115 /// #![feature(f16)]
2116 /// # #[cfg(target_has_reliable_f16)] {
2117 ///
2118 /// let x = 8.0f16;
2119 ///
2120 /// // x^(1/3) - 2 == 0
2121 /// let abs_difference = (x.cbrt() - 2.0).abs();
2122 ///
2123 /// assert!(abs_difference <= f16::EPSILON);
2124 /// # }
2125 /// ```
2126 #[inline]
2127 #[rustc_allow_incoherent_impl]
2128 #[unstable(feature = "f16", issue = "116909")]
2129 #[must_use = "method returns a new number and does not mutate the original value"]
2130 pub fn cbrt(self) -> f16 {
2131 libm::cbrtf(self as f32) as f16
2132 }
2133}