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 #[ferrocene::prevalidated]
570 #[inline]
571 #[unstable(feature = "f16", issue = "116909")]
572 #[must_use]
573 pub const fn classify(self) -> FpCategory {
574 let b = self.to_bits();
575 match (b & Self::MANTISSA_MASK, b & Self::EXPONENT_MASK) {
576 (0, Self::EXPONENT_MASK) => FpCategory::Infinite,
577 (_, Self::EXPONENT_MASK) => FpCategory::Nan,
578 (0, 0) => FpCategory::Zero,
579 (_, 0) => FpCategory::Subnormal,
580 _ => FpCategory::Normal,
581 }
582 }
583
584 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
585 /// positive sign bit and positive infinity.
586 ///
587 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
588 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
589 /// conserved over arithmetic operations, the result of `is_sign_positive` on
590 /// a NaN might produce an unexpected or non-portable result. See the [specification
591 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
592 /// if you need fully portable behavior (will return NaN for all NaNs).
593 ///
594 /// ```
595 /// #![feature(f16)]
596 /// # #[cfg(target_has_reliable_f16)] {
597 ///
598 /// let f = 7.0_f16;
599 /// let g = -7.0_f16;
600 ///
601 /// assert!(f.is_sign_positive());
602 /// assert!(!g.is_sign_positive());
603 /// # }
604 /// ```
605 #[inline]
606 #[must_use]
607 #[unstable(feature = "f16", issue = "116909")]
608 pub const fn is_sign_positive(self) -> bool {
609 !self.is_sign_negative()
610 }
611
612 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
613 /// negative sign bit and negative infinity.
614 ///
615 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
616 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
617 /// conserved over arithmetic operations, the result of `is_sign_negative` on
618 /// a NaN might produce an unexpected or non-portable result. See the [specification
619 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
620 /// if you need fully portable behavior (will return NaN for all NaNs).
621 ///
622 /// ```
623 /// #![feature(f16)]
624 /// # #[cfg(target_has_reliable_f16)] {
625 ///
626 /// let f = 7.0_f16;
627 /// let g = -7.0_f16;
628 ///
629 /// assert!(!f.is_sign_negative());
630 /// assert!(g.is_sign_negative());
631 /// # }
632 /// ```
633 #[inline]
634 #[must_use]
635 #[unstable(feature = "f16", issue = "116909")]
636 pub const fn is_sign_negative(self) -> bool {
637 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
638 // applies to zeros and NaNs as well.
639 // SAFETY: This is just transmuting to get the sign bit, it's fine.
640 (self.to_bits() & (1 << 15)) != 0
641 }
642
643 /// Returns the least number greater than `self`.
644 ///
645 /// Let `TINY` be the smallest representable positive `f16`. Then,
646 /// - if `self.is_nan()`, this returns `self`;
647 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
648 /// - if `self` is `-TINY`, this returns -0.0;
649 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
650 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
651 /// - otherwise the unique least value greater than `self` is returned.
652 ///
653 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
654 /// is finite `x == x.next_up().next_down()` also holds.
655 ///
656 /// ```rust
657 /// #![feature(f16)]
658 /// # #[cfg(target_has_reliable_f16)] {
659 ///
660 /// // f16::EPSILON is the difference between 1.0 and the next number up.
661 /// assert_eq!(1.0f16.next_up(), 1.0 + f16::EPSILON);
662 /// // But not for most numbers.
663 /// assert!(0.1f16.next_up() < 0.1 + f16::EPSILON);
664 /// assert_eq!(4356f16.next_up(), 4360.0);
665 /// # }
666 /// ```
667 ///
668 /// This operation corresponds to IEEE-754 `nextUp`.
669 ///
670 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
671 /// [`INFINITY`]: Self::INFINITY
672 /// [`MIN`]: Self::MIN
673 /// [`MAX`]: Self::MAX
674 #[inline]
675 #[doc(alias = "nextUp")]
676 #[unstable(feature = "f16", issue = "116909")]
677 #[must_use = "method returns a new number and does not mutate the original value"]
678 pub const fn next_up(self) -> Self {
679 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
680 // denormals to zero. This is in general unsound and unsupported, but here
681 // we do our best to still produce the correct result on such targets.
682 let bits = self.to_bits();
683 if self.is_nan() || bits == Self::INFINITY.to_bits() {
684 return self;
685 }
686
687 let abs = bits & !Self::SIGN_MASK;
688 let next_bits = if abs == 0 {
689 Self::TINY_BITS
690 } else if bits == abs {
691 bits + 1
692 } else {
693 bits - 1
694 };
695 Self::from_bits(next_bits)
696 }
697
698 /// Returns the greatest number less than `self`.
699 ///
700 /// Let `TINY` be the smallest representable positive `f16`. Then,
701 /// - if `self.is_nan()`, this returns `self`;
702 /// - if `self` is [`INFINITY`], this returns [`MAX`];
703 /// - if `self` is `TINY`, this returns 0.0;
704 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
705 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
706 /// - otherwise the unique greatest value less than `self` is returned.
707 ///
708 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
709 /// is finite `x == x.next_down().next_up()` also holds.
710 ///
711 /// ```rust
712 /// #![feature(f16)]
713 /// # #[cfg(target_has_reliable_f16)] {
714 ///
715 /// let x = 1.0f16;
716 /// // Clamp value into range [0, 1).
717 /// let clamped = x.clamp(0.0, 1.0f16.next_down());
718 /// assert!(clamped < 1.0);
719 /// assert_eq!(clamped.next_up(), 1.0);
720 /// # }
721 /// ```
722 ///
723 /// This operation corresponds to IEEE-754 `nextDown`.
724 ///
725 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
726 /// [`INFINITY`]: Self::INFINITY
727 /// [`MIN`]: Self::MIN
728 /// [`MAX`]: Self::MAX
729 #[inline]
730 #[doc(alias = "nextDown")]
731 #[unstable(feature = "f16", issue = "116909")]
732 #[must_use = "method returns a new number and does not mutate the original value"]
733 pub const fn next_down(self) -> Self {
734 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
735 // denormals to zero. This is in general unsound and unsupported, but here
736 // we do our best to still produce the correct result on such targets.
737 let bits = self.to_bits();
738 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
739 return self;
740 }
741
742 let abs = bits & !Self::SIGN_MASK;
743 let next_bits = if abs == 0 {
744 Self::NEG_TINY_BITS
745 } else if bits == abs {
746 bits - 1
747 } else {
748 bits + 1
749 };
750 Self::from_bits(next_bits)
751 }
752
753 /// Takes the reciprocal (inverse) of a number, `1/x`.
754 ///
755 /// ```
756 /// #![feature(f16)]
757 /// # #[cfg(target_has_reliable_f16)] {
758 ///
759 /// let x = 2.0_f16;
760 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
761 ///
762 /// assert!(abs_difference <= f16::EPSILON);
763 /// # }
764 /// ```
765 #[inline]
766 #[unstable(feature = "f16", issue = "116909")]
767 #[must_use = "this returns the result of the operation, without modifying the original"]
768 pub const fn recip(self) -> Self {
769 1.0 / self
770 }
771
772 /// Converts radians to degrees.
773 ///
774 /// # Unspecified precision
775 ///
776 /// The precision of this function is non-deterministic. This means it varies by platform,
777 /// Rust version, and can even differ within the same execution from one invocation to the next.
778 ///
779 /// # Examples
780 ///
781 /// ```
782 /// #![feature(f16)]
783 /// # #[cfg(target_has_reliable_f16)] {
784 ///
785 /// let angle = std::f16::consts::PI;
786 ///
787 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
788 /// assert!(abs_difference <= 0.5);
789 /// # }
790 /// ```
791 #[inline]
792 #[unstable(feature = "f16", issue = "116909")]
793 #[must_use = "this returns the result of the operation, without modifying the original"]
794 pub const fn to_degrees(self) -> Self {
795 // Use a literal to avoid double rounding, consts::PI is already rounded,
796 // and dividing would round again.
797 const PIS_IN_180: f16 = 57.2957795130823208767981548141051703_f16;
798 self * PIS_IN_180
799 }
800
801 /// Converts degrees to radians.
802 ///
803 /// # Unspecified precision
804 ///
805 /// The precision of this function is non-deterministic. This means it varies by platform,
806 /// Rust version, and can even differ within the same execution from one invocation to the next.
807 ///
808 /// # Examples
809 ///
810 /// ```
811 /// #![feature(f16)]
812 /// # #[cfg(target_has_reliable_f16)] {
813 ///
814 /// let angle = 180.0f16;
815 ///
816 /// let abs_difference = (angle.to_radians() - std::f16::consts::PI).abs();
817 ///
818 /// assert!(abs_difference <= 0.01);
819 /// # }
820 /// ```
821 #[inline]
822 #[unstable(feature = "f16", issue = "116909")]
823 #[must_use = "this returns the result of the operation, without modifying the original"]
824 pub const fn to_radians(self) -> f16 {
825 // Use a literal to avoid double rounding, consts::PI is already rounded,
826 // and dividing would round again.
827 const RADS_PER_DEG: f16 = 0.017453292519943295769236907684886_f16;
828 self * RADS_PER_DEG
829 }
830
831 /// Returns the maximum of the two numbers, ignoring NaN.
832 ///
833 /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
834 /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
835 /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
836 /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
837 /// non-deterministically.
838 ///
839 /// The handling of NaNs follows the IEEE 754-2019 semantics for `maximumNumber`, treating all
840 /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
841 /// follows the IEEE 754-2008 semantics for `maxNum`.
842 ///
843 /// ```
844 /// #![feature(f16)]
845 /// # #[cfg(target_has_reliable_f16)] {
846 ///
847 /// let x = 1.0f16;
848 /// let y = 2.0f16;
849 ///
850 /// assert_eq!(x.max(y), y);
851 /// assert_eq!(x.max(f16::NAN), x);
852 /// # }
853 /// ```
854 #[inline]
855 #[unstable(feature = "f16", issue = "116909")]
856 #[rustc_const_unstable(feature = "f16", issue = "116909")]
857 #[must_use = "this returns the result of the comparison, without modifying either input"]
858 pub const fn max(self, other: f16) -> f16 {
859 intrinsics::maximum_number_nsz_f16(self, other)
860 }
861
862 /// Returns the minimum of the two numbers, ignoring NaN.
863 ///
864 /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
865 /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
866 /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
867 /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
868 /// non-deterministically.
869 ///
870 /// The handling of NaNs follows the IEEE 754-2019 semantics for `minimumNumber`, treating all
871 /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
872 /// follows the IEEE 754-2008 semantics for `minNum`.
873 ///
874 /// ```
875 /// #![feature(f16)]
876 /// # #[cfg(target_has_reliable_f16)] {
877 ///
878 /// let x = 1.0f16;
879 /// let y = 2.0f16;
880 ///
881 /// assert_eq!(x.min(y), x);
882 /// assert_eq!(x.min(f16::NAN), x);
883 /// # }
884 /// ```
885 #[inline]
886 #[unstable(feature = "f16", issue = "116909")]
887 #[rustc_const_unstable(feature = "f16", issue = "116909")]
888 #[must_use = "this returns the result of the comparison, without modifying either input"]
889 pub const fn min(self, other: f16) -> f16 {
890 intrinsics::minimum_number_nsz_f16(self, other)
891 }
892
893 /// Returns the maximum of the two numbers, propagating NaN.
894 ///
895 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
896 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
897 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
898 /// non-NaN inputs.
899 ///
900 /// This is in contrast to [`f16::max`] which only returns NaN when *both* arguments are NaN,
901 /// and which does not reliably order `-0.0` and `+0.0`.
902 ///
903 /// This follows the IEEE 754-2019 semantics for `maximum`.
904 ///
905 /// ```
906 /// #![feature(f16)]
907 /// #![feature(float_minimum_maximum)]
908 /// # #[cfg(target_has_reliable_f16)] {
909 ///
910 /// let x = 1.0f16;
911 /// let y = 2.0f16;
912 ///
913 /// assert_eq!(x.maximum(y), y);
914 /// assert!(x.maximum(f16::NAN).is_nan());
915 /// # }
916 /// ```
917 #[inline]
918 #[unstable(feature = "f16", issue = "116909")]
919 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
920 #[must_use = "this returns the result of the comparison, without modifying either input"]
921 pub const fn maximum(self, other: f16) -> f16 {
922 intrinsics::maximumf16(self, other)
923 }
924
925 /// Returns the minimum of the two numbers, propagating NaN.
926 ///
927 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
928 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
929 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
930 /// non-NaN inputs.
931 ///
932 /// This is in contrast to [`f16::min`] which only returns NaN when *both* arguments are NaN,
933 /// and which does not reliably order `-0.0` and `+0.0`.
934 ///
935 /// This follows the IEEE 754-2019 semantics for `minimum`.
936 ///
937 /// ```
938 /// #![feature(f16)]
939 /// #![feature(float_minimum_maximum)]
940 /// # #[cfg(target_has_reliable_f16)] {
941 ///
942 /// let x = 1.0f16;
943 /// let y = 2.0f16;
944 ///
945 /// assert_eq!(x.minimum(y), x);
946 /// assert!(x.minimum(f16::NAN).is_nan());
947 /// # }
948 /// ```
949 #[inline]
950 #[unstable(feature = "f16", issue = "116909")]
951 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
952 #[must_use = "this returns the result of the comparison, without modifying either input"]
953 pub const fn minimum(self, other: f16) -> f16 {
954 intrinsics::minimumf16(self, other)
955 }
956
957 /// Calculates the midpoint (average) between `self` and `rhs`.
958 ///
959 /// This returns NaN when *either* argument is NaN or if a combination of
960 /// +inf and -inf is provided as arguments.
961 ///
962 /// # Examples
963 ///
964 /// ```
965 /// #![feature(f16)]
966 /// # #[cfg(target_has_reliable_f16)] {
967 ///
968 /// assert_eq!(1f16.midpoint(4.0), 2.5);
969 /// assert_eq!((-5.5f16).midpoint(8.0), 1.25);
970 /// # }
971 /// ```
972 #[inline]
973 #[doc(alias = "average")]
974 #[unstable(feature = "f16", issue = "116909")]
975 #[rustc_const_unstable(feature = "f16", issue = "116909")]
976 #[must_use = "this returns the result of the operation, \
977 without modifying the original"]
978 pub const fn midpoint(self, other: f16) -> f16 {
979 const HI: f16 = f16::MAX * 0.5;
980
981 let (a, b) = (self, other);
982 let abs_a = a.abs();
983 let abs_b = b.abs();
984
985 if abs_a <= HI && abs_b <= HI {
986 // Overflow is impossible
987 (a + b) * 0.5
988 } else {
989 (a * 0.5) + (b * 0.5)
990 }
991 }
992
993 /// Rounds toward zero and converts to any primitive integer type,
994 /// assuming that the value is finite and fits in that type.
995 ///
996 /// ```
997 /// #![feature(f16)]
998 /// # #[cfg(target_has_reliable_f16)] {
999 ///
1000 /// let value = 4.6_f16;
1001 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1002 /// assert_eq!(rounded, 4);
1003 ///
1004 /// let value = -128.9_f16;
1005 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1006 /// assert_eq!(rounded, i8::MIN);
1007 /// # }
1008 /// ```
1009 ///
1010 /// # Safety
1011 ///
1012 /// The value must:
1013 ///
1014 /// * Not be `NaN`
1015 /// * Not be infinite
1016 /// * Be representable in the return type `Int`, after truncating off its fractional part
1017 #[inline]
1018 #[unstable(feature = "f16", issue = "116909")]
1019 #[must_use = "this returns the result of the operation, without modifying the original"]
1020 pub unsafe fn to_int_unchecked<Int>(self) -> Int
1021 where
1022 Self: FloatToInt<Int>,
1023 {
1024 // SAFETY: the caller must uphold the safety contract for
1025 // `FloatToInt::to_int_unchecked`.
1026 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1027 }
1028
1029 /// Converts to the target float type, rounding as defined in IEEE 754.
1030 ///
1031 /// This is equivalent to `self as Flt`. Narrowing to a smaller type can
1032 /// produce an infinity.
1033 ///
1034 /// ```
1035 /// #![feature(float_conversions, f16)]
1036 /// # #[cfg(target_has_reliable_f16)] {
1037 ///
1038 /// let x = 1.5_f16;
1039 /// assert_eq!(x.cast::<f32>(), 1.5_f32);
1040 /// # }
1041 /// ```
1042 #[unstable(feature = "float_conversions", issue = "159913")]
1043 #[must_use = "this returns the result of the operation, without modifying the original"]
1044 #[inline]
1045 pub fn cast<Flt>(self) -> Flt
1046 where
1047 Self: FloatToFloat<Flt>,
1048 {
1049 FloatToFloat::<Flt>::cast(self)
1050 }
1051
1052 /// Rounds toward zero and converts to any primitive integer type, saturating
1053 /// at the type's boundaries and mapping `NaN` to zero.
1054 ///
1055 /// This is equivalent to `self as Int`.
1056 ///
1057 /// ```
1058 /// #![feature(float_conversions, f16)]
1059 /// # #[cfg(target_has_reliable_f16)] {
1060 ///
1061 /// assert_eq!(4.6_f16.to_int_saturating::<u8>(), 4);
1062 /// assert_eq!(f16::NAN.to_int_saturating::<u8>(), 0);
1063 /// # }
1064 /// ```
1065 #[unstable(feature = "float_conversions", issue = "159913")]
1066 #[must_use = "this returns the result of the operation, without modifying the original"]
1067 #[inline]
1068 pub fn to_int_saturating<Int>(self) -> Int
1069 where
1070 Self: FloatToInt<Int>,
1071 {
1072 FloatToInt::<Int>::to_int_saturating(self)
1073 }
1074
1075 /// Rounds toward zero and converts to any primitive integer type, returning
1076 /// `None` if the value is `NaN`, infinite, or does not fit in the target type.
1077 ///
1078 /// ```
1079 /// #![feature(float_conversions, f16)]
1080 /// # #[cfg(target_has_reliable_f16)] {
1081 ///
1082 /// assert_eq!(4.6_f16.to_int_checked::<u8>(), Some(4));
1083 /// assert_eq!(f16::NAN.to_int_checked::<u8>(), None);
1084 /// # }
1085 /// ```
1086 #[unstable(feature = "float_conversions", issue = "159913")]
1087 #[must_use = "this returns the result of the operation, without modifying the original"]
1088 #[inline]
1089 pub fn to_int_checked<Int>(self) -> Option<Int>
1090 where
1091 Self: FloatToInt<Int>,
1092 {
1093 FloatToInt::<Int>::to_int_checked(self)
1094 }
1095
1096 /// Rounds toward zero and converts to any primitive integer type.
1097 ///
1098 /// This is equivalent to `self.to_int_checked().unwrap()`.
1099 ///
1100 /// # Panics
1101 ///
1102 /// Panics if the value is `NaN`, infinite, or does not fit in the target type.
1103 ///
1104 /// ```
1105 /// #![feature(float_conversions, f16)]
1106 /// # #[cfg(target_has_reliable_f16)] {
1107 ///
1108 /// assert_eq!(4.6_f16.to_int_strict::<u8>(), 4);
1109 /// # }
1110 /// ```
1111 #[unstable(feature = "float_conversions", issue = "159913")]
1112 #[must_use = "this returns the result of the operation, without modifying the original"]
1113 #[inline]
1114 #[track_caller]
1115 pub fn to_int_strict<Int>(self) -> Int
1116 where
1117 Self: FloatToInt<Int>,
1118 {
1119 self.to_int_checked::<Int>()
1120 .expect("the value cannot be represented in the target integer type")
1121 }
1122
1123 /// Raw transmutation to `u16`.
1124 ///
1125 /// This is currently identical to `transmute::<f16, u16>(self)` on all platforms.
1126 ///
1127 /// See [`from_bits`](#method.from_bits) for some discussion of the
1128 /// portability of this operation (there are almost no issues).
1129 ///
1130 /// Note that this function is distinct from `as` casting, which attempts to
1131 /// preserve the *numeric* value, and not the bitwise value.
1132 ///
1133 /// ```
1134 /// #![feature(f16)]
1135 /// # #[cfg(target_has_reliable_f16)] {
1136 ///
1137 /// assert_ne!((1f16).to_bits(), 1f16 as u16); // to_bits() is not casting!
1138 /// assert_eq!((12.5f16).to_bits(), 0x4a40);
1139 /// # }
1140 /// ```
1141 #[inline]
1142 #[unstable(feature = "f16", issue = "116909")]
1143 #[must_use = "this returns the result of the operation, without modifying the original"]
1144 #[allow(unnecessary_transmutes)]
1145 #[ferrocene::prevalidated]
1146 pub const fn to_bits(self) -> u16 {
1147 // SAFETY: `u16` is a plain old datatype so we can always transmute to it.
1148 unsafe { mem::transmute(self) }
1149 }
1150
1151 /// Raw transmutation from `u16`.
1152 ///
1153 /// This is currently identical to `transmute::<u16, f16>(v)` on all platforms.
1154 /// It turns out this is incredibly portable, for two reasons:
1155 ///
1156 /// * Floats and Ints have the same endianness on all supported platforms.
1157 /// * IEEE 754 very precisely specifies the bit layout of floats.
1158 ///
1159 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1160 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1161 /// (notably x86 and ARM) picked the interpretation that was ultimately
1162 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1163 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1164 ///
1165 /// Rather than trying to preserve signaling-ness cross-platform, this
1166 /// implementation favors preserving the exact bits. This means that
1167 /// any payloads encoded in NaNs will be preserved even if the result of
1168 /// this method is sent over the network from an x86 machine to a MIPS one.
1169 ///
1170 /// If the results of this method are only manipulated by the same
1171 /// architecture that produced them, then there is no portability concern.
1172 ///
1173 /// If the input isn't NaN, then there is no portability concern.
1174 ///
1175 /// If you don't care about signalingness (very likely), then there is no
1176 /// portability concern.
1177 ///
1178 /// Note that this function is distinct from `as` casting, which attempts to
1179 /// preserve the *numeric* value, and not the bitwise value.
1180 ///
1181 /// ```
1182 /// #![feature(f16)]
1183 /// # #[cfg(target_has_reliable_f16)] {
1184 ///
1185 /// let v = f16::from_bits(0x4a40);
1186 /// assert_eq!(v, 12.5);
1187 /// # }
1188 /// ```
1189 #[inline]
1190 #[must_use]
1191 #[unstable(feature = "f16", issue = "116909")]
1192 #[allow(unnecessary_transmutes)]
1193 #[ferrocene::prevalidated]
1194 pub const fn from_bits(v: u16) -> Self {
1195 // It turns out the safety issues with sNaN were overblown! Hooray!
1196 // SAFETY: `u16` is a plain old datatype so we can always transmute from it.
1197 unsafe { mem::transmute(v) }
1198 }
1199
1200 /// Returns the memory representation of this floating point number as a byte array in
1201 /// big-endian (network) byte order.
1202 ///
1203 /// See [`from_bits`](Self::from_bits) for some discussion of the
1204 /// portability of this operation (there are almost no issues).
1205 ///
1206 /// # Examples
1207 ///
1208 /// ```
1209 /// #![feature(f16)]
1210 /// # #[cfg(target_has_reliable_f16)] {
1211 ///
1212 /// let bytes = 12.5f16.to_be_bytes();
1213 /// assert_eq!(bytes, [0x4a, 0x40]);
1214 /// # }
1215 /// ```
1216 #[inline]
1217 #[unstable(feature = "f16", issue = "116909")]
1218 #[must_use = "this returns the result of the operation, without modifying the original"]
1219 pub const fn to_be_bytes(self) -> [u8; 2] {
1220 self.to_bits().to_be_bytes()
1221 }
1222
1223 /// Returns the memory representation of this floating point number as a byte array in
1224 /// little-endian byte order.
1225 ///
1226 /// See [`from_bits`](Self::from_bits) for some discussion of the
1227 /// portability of this operation (there are almost no issues).
1228 ///
1229 /// # Examples
1230 ///
1231 /// ```
1232 /// #![feature(f16)]
1233 /// # #[cfg(target_has_reliable_f16)] {
1234 ///
1235 /// let bytes = 12.5f16.to_le_bytes();
1236 /// assert_eq!(bytes, [0x40, 0x4a]);
1237 /// # }
1238 /// ```
1239 #[inline]
1240 #[unstable(feature = "f16", issue = "116909")]
1241 #[must_use = "this returns the result of the operation, without modifying the original"]
1242 pub const fn to_le_bytes(self) -> [u8; 2] {
1243 self.to_bits().to_le_bytes()
1244 }
1245
1246 /// Returns the memory representation of this floating point number as a byte array in
1247 /// native byte order.
1248 ///
1249 /// As the target platform's native endianness is used, portable code
1250 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1251 ///
1252 /// [`to_be_bytes`]: f16::to_be_bytes
1253 /// [`to_le_bytes`]: f16::to_le_bytes
1254 ///
1255 /// See [`from_bits`](Self::from_bits) for some discussion of the
1256 /// portability of this operation (there are almost no issues).
1257 ///
1258 /// # Examples
1259 ///
1260 /// ```
1261 /// #![feature(f16)]
1262 /// # #[cfg(target_has_reliable_f16)] {
1263 ///
1264 /// let bytes = 12.5f16.to_ne_bytes();
1265 /// assert_eq!(
1266 /// bytes,
1267 /// if cfg!(target_endian = "big") {
1268 /// [0x4a, 0x40]
1269 /// } else {
1270 /// [0x40, 0x4a]
1271 /// }
1272 /// );
1273 /// # }
1274 /// ```
1275 #[inline]
1276 #[unstable(feature = "f16", issue = "116909")]
1277 #[must_use = "this returns the result of the operation, without modifying the original"]
1278 pub const fn to_ne_bytes(self) -> [u8; 2] {
1279 self.to_bits().to_ne_bytes()
1280 }
1281
1282 /// Creates a floating point value from its representation as a byte array in big endian.
1283 ///
1284 /// See [`from_bits`](Self::from_bits) for some discussion of the
1285 /// portability of this operation (there are almost no issues).
1286 ///
1287 /// # Examples
1288 ///
1289 /// ```
1290 /// #![feature(f16)]
1291 /// # #[cfg(target_has_reliable_f16)] {
1292 ///
1293 /// let value = f16::from_be_bytes([0x4a, 0x40]);
1294 /// assert_eq!(value, 12.5);
1295 /// # }
1296 /// ```
1297 #[inline]
1298 #[must_use]
1299 #[unstable(feature = "f16", issue = "116909")]
1300 pub const fn from_be_bytes(bytes: [u8; 2]) -> Self {
1301 Self::from_bits(u16::from_be_bytes(bytes))
1302 }
1303
1304 /// Creates a floating point value from its representation as a byte array in little endian.
1305 ///
1306 /// See [`from_bits`](Self::from_bits) for some discussion of the
1307 /// portability of this operation (there are almost no issues).
1308 ///
1309 /// # Examples
1310 ///
1311 /// ```
1312 /// #![feature(f16)]
1313 /// # #[cfg(target_has_reliable_f16)] {
1314 ///
1315 /// let value = f16::from_le_bytes([0x40, 0x4a]);
1316 /// assert_eq!(value, 12.5);
1317 /// # }
1318 /// ```
1319 #[inline]
1320 #[must_use]
1321 #[unstable(feature = "f16", issue = "116909")]
1322 pub const fn from_le_bytes(bytes: [u8; 2]) -> Self {
1323 Self::from_bits(u16::from_le_bytes(bytes))
1324 }
1325
1326 /// Creates a floating point value from its representation as a byte array in native endian.
1327 ///
1328 /// As the target platform's native endianness is used, portable code
1329 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1330 /// appropriate instead.
1331 ///
1332 /// [`from_be_bytes`]: f16::from_be_bytes
1333 /// [`from_le_bytes`]: f16::from_le_bytes
1334 ///
1335 /// See [`from_bits`](Self::from_bits) for some discussion of the
1336 /// portability of this operation (there are almost no issues).
1337 ///
1338 /// # Examples
1339 ///
1340 /// ```
1341 /// #![feature(f16)]
1342 /// # #[cfg(target_has_reliable_f16)] {
1343 ///
1344 /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") {
1345 /// [0x4a, 0x40]
1346 /// } else {
1347 /// [0x40, 0x4a]
1348 /// });
1349 /// assert_eq!(value, 12.5);
1350 /// # }
1351 /// ```
1352 #[inline]
1353 #[must_use]
1354 #[unstable(feature = "f16", issue = "116909")]
1355 pub const fn from_ne_bytes(bytes: [u8; 2]) -> Self {
1356 Self::from_bits(u16::from_ne_bytes(bytes))
1357 }
1358
1359 /// Returns the ordering between `self` and `other`.
1360 ///
1361 /// Unlike the standard partial comparison between floating point numbers,
1362 /// this comparison always produces an ordering in accordance to
1363 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1364 /// floating point standard. The values are ordered in the following sequence:
1365 ///
1366 /// - negative quiet NaN
1367 /// - negative signaling NaN
1368 /// - negative infinity
1369 /// - negative numbers
1370 /// - negative subnormal numbers
1371 /// - negative zero
1372 /// - positive zero
1373 /// - positive subnormal numbers
1374 /// - positive numbers
1375 /// - positive infinity
1376 /// - positive signaling NaN
1377 /// - positive quiet NaN.
1378 ///
1379 /// The ordering established by this function does not always agree with the
1380 /// [`PartialOrd`] and [`PartialEq`] implementations of `f16`. For example,
1381 /// they consider negative and positive zero equal, while `total_cmp`
1382 /// doesn't.
1383 ///
1384 /// The interpretation of the signaling NaN bit follows the definition in
1385 /// the IEEE 754 standard, which may not match the interpretation by some of
1386 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1387 ///
1388 /// # Example
1389 ///
1390 /// ```
1391 /// #![feature(f16)]
1392 /// # #[cfg(target_has_reliable_f16)] {
1393 ///
1394 /// struct GoodBoy {
1395 /// name: &'static str,
1396 /// weight: f16,
1397 /// }
1398 ///
1399 /// let mut bois = vec![
1400 /// GoodBoy { name: "Pucci", weight: 0.1 },
1401 /// GoodBoy { name: "Woofer", weight: 99.0 },
1402 /// GoodBoy { name: "Yapper", weight: 10.0 },
1403 /// GoodBoy { name: "Chonk", weight: f16::INFINITY },
1404 /// GoodBoy { name: "Abs. Unit", weight: f16::NAN },
1405 /// GoodBoy { name: "Floaty", weight: -5.0 },
1406 /// ];
1407 ///
1408 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1409 ///
1410 /// // `f16::NAN` could be positive or negative, which will affect the sort order.
1411 /// if f16::NAN.is_sign_negative() {
1412 /// bois.into_iter().map(|b| b.weight)
1413 /// .zip([f16::NAN, -5.0, 0.1, 10.0, 99.0, f16::INFINITY].iter())
1414 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1415 /// } else {
1416 /// bois.into_iter().map(|b| b.weight)
1417 /// .zip([-5.0, 0.1, 10.0, 99.0, f16::INFINITY, f16::NAN].iter())
1418 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1419 /// }
1420 /// # }
1421 /// ```
1422 #[inline]
1423 #[must_use]
1424 #[unstable(feature = "f16", issue = "116909")]
1425 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1426 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1427 let mut left = self.to_bits() as i16;
1428 let mut right = other.to_bits() as i16;
1429
1430 // In case of negatives, flip all the bits except the sign
1431 // to achieve a similar layout as two's complement integers
1432 //
1433 // Why does this work? IEEE 754 floats consist of three fields:
1434 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1435 // fields as a whole have the property that their bitwise order is
1436 // equal to the numeric magnitude where the magnitude is defined.
1437 // The magnitude is not normally defined on NaN values, but
1438 // IEEE 754 totalOrder defines the NaN values also to follow the
1439 // bitwise order. This leads to order explained in the doc comment.
1440 // However, the representation of magnitude is the same for negative
1441 // and positive numbers – only the sign bit is different.
1442 // To easily compare the floats as signed integers, we need to
1443 // flip the exponent and mantissa bits in case of negative numbers.
1444 // We effectively convert the numbers to "two's complement" form.
1445 //
1446 // To do the flipping, we construct a mask and XOR against it.
1447 // We branchlessly calculate an "all-ones except for the sign bit"
1448 // mask from negative-signed values: right shifting sign-extends
1449 // the integer, so we "fill" the mask with sign bits, and then
1450 // convert to unsigned to push one more zero bit.
1451 // On positive values, the mask is all zeros, so it's a no-op.
1452 left ^= (((left >> 15) as u16) >> 1) as i16;
1453 right ^= (((right >> 15) as u16) >> 1) as i16;
1454
1455 left.cmp(&right)
1456 }
1457
1458 /// Restrict a value to a certain interval unless it is NaN.
1459 ///
1460 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1461 /// less than `min`. Otherwise this returns `self`.
1462 ///
1463 /// Note that this function returns NaN if the initial value was NaN as
1464 /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1465 /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1466 ///
1467 /// # Panics
1468 ///
1469 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1470 ///
1471 /// # Examples
1472 ///
1473 /// ```
1474 /// #![feature(f16)]
1475 /// # #[cfg(target_has_reliable_f16_math)] {
1476 ///
1477 /// assert!((-3.0f16).clamp(-2.0, 1.0) == -2.0);
1478 /// assert!((0.0f16).clamp(-2.0, 1.0) == 0.0);
1479 /// assert!((2.0f16).clamp(-2.0, 1.0) == 1.0);
1480 /// assert!((f16::NAN).clamp(-2.0, 1.0).is_nan());
1481 ///
1482 /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1483 /// assert!((0.0f16).clamp(-0.0, -0.0) == 0.0);
1484 /// assert!((1.0f16).clamp(-0.0, 0.0) == 0.0);
1485 /// // This is definitely a negative zero.
1486 /// assert!((-1.0f16).clamp(-0.0, 1.0).is_sign_negative());
1487 /// # }
1488 /// ```
1489 #[inline]
1490 #[unstable(feature = "f16", issue = "116909")]
1491 #[must_use = "method returns a new number and does not mutate the original value"]
1492 #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1493 pub const fn clamp(mut self, min: f16, max: f16) -> f16 {
1494 const_assert!(
1495 min <= max,
1496 "min > max, or either was NaN",
1497 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1498 min: f16,
1499 max: f16,
1500 );
1501
1502 if self < min {
1503 self = min;
1504 }
1505 if self > max {
1506 self = max;
1507 }
1508 self
1509 }
1510
1511 /// Clamps this number to a symmetric range centered around zero.
1512 ///
1513 /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1514 ///
1515 /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1516 /// explicit about the intent.
1517 ///
1518 /// # Panics
1519 ///
1520 /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1521 ///
1522 /// # Examples
1523 ///
1524 /// ```
1525 /// #![feature(f16)]
1526 /// #![feature(clamp_magnitude)]
1527 /// # #[cfg(target_has_reliable_f16)] {
1528 /// assert_eq!(5.0f16.clamp_magnitude(3.0), 3.0);
1529 /// assert_eq!((-5.0f16).clamp_magnitude(3.0), -3.0);
1530 /// assert_eq!(2.0f16.clamp_magnitude(3.0), 2.0);
1531 /// assert_eq!((-2.0f16).clamp_magnitude(3.0), -2.0);
1532 /// # }
1533 /// ```
1534 #[inline]
1535 #[unstable(feature = "clamp_magnitude", issue = "148519")]
1536 #[must_use = "this returns the clamped value and does not modify the original"]
1537 #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1538 pub fn clamp_magnitude(self, limit: f16) -> f16 {
1539 assert!(limit >= 0.0, "limit must be non-negative and not NaN");
1540 let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1541 self.clamp(-limit, limit)
1542 }
1543
1544 /// Restrict a value to a certain range, unless it is NaN.
1545 ///
1546 /// This is largely equal to `max`, `min`, or `clamp`, depending on whether the range is
1547 /// `min..`, `..=max`, or `min..=max`, respectively. However, unlike `max` and `min`, it will
1548 /// panic if any bound is NaN.
1549 ///
1550 /// Note that this function returns NaN if the initial value was NaN as
1551 /// well.
1552 ///
1553 /// Exclusive ranges are not permitted.
1554 ///
1555 /// # Panics
1556 ///
1557 /// Panics on `min..=max` if `min > max`, or if any bound is NaN.
1558 ///
1559 /// # Examples
1560 ///
1561 /// ```
1562 /// #![feature(f16, clamp_to)]
1563 /// # #[cfg(target_has_reliable_f16_math)] {
1564 /// assert_eq!((-3.0f16).clamp_to(-2.0..=1.0), -2.0);
1565 /// assert_eq!(0.0f16.clamp_to(-2.0..=1.0), 0.0);
1566 /// assert_eq!(2.0f16.clamp_to(..=1.0), 1.0);
1567 /// assert_eq!(5.0f16.clamp_to(7.0..), 7.0);
1568 /// assert!(f16::NAN.clamp_to(1.0..=2.0).is_nan());
1569 /// # }
1570 /// ```
1571 #[must_use]
1572 #[inline]
1573 #[unstable(feature = "clamp_to", issue = "147781")]
1574 pub fn clamp_to<R>(self, range: R) -> Self
1575 where
1576 R: crate::cmp::ClampBounds<Self>,
1577 {
1578 range.clamp(self)
1579 }
1580
1581 /// Computes the absolute value of `self`.
1582 ///
1583 /// This function always returns the precise result.
1584 ///
1585 /// # Examples
1586 ///
1587 /// ```
1588 /// #![feature(f16)]
1589 /// # #[cfg(target_has_reliable_f16)] {
1590 ///
1591 /// let x = 3.5_f16;
1592 /// let y = -3.5_f16;
1593 ///
1594 /// assert_eq!(x.abs(), x);
1595 /// assert_eq!(y.abs(), -y);
1596 ///
1597 /// assert!(f16::NAN.abs().is_nan());
1598 /// # }
1599 /// ```
1600 #[inline]
1601 #[unstable(feature = "f16", issue = "116909")]
1602 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1603 #[must_use = "method returns a new number and does not mutate the original value"]
1604 #[ferrocene::prevalidated]
1605 pub const fn abs(self) -> Self {
1606 intrinsics::fabs(self)
1607 }
1608
1609 /// Returns a number that represents the sign of `self`.
1610 ///
1611 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1612 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1613 /// - NaN if the number is NaN
1614 ///
1615 /// # Examples
1616 ///
1617 /// ```
1618 /// #![feature(f16)]
1619 /// # #[cfg(target_has_reliable_f16)] {
1620 ///
1621 /// let f = 3.5_f16;
1622 ///
1623 /// assert_eq!(f.signum(), 1.0);
1624 /// assert_eq!(f16::NEG_INFINITY.signum(), -1.0);
1625 ///
1626 /// assert!(f16::NAN.signum().is_nan());
1627 /// # }
1628 /// ```
1629 #[inline]
1630 #[unstable(feature = "f16", issue = "116909")]
1631 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1632 #[must_use = "method returns a new number and does not mutate the original value"]
1633 pub const fn signum(self) -> f16 {
1634 if self.is_nan() { Self::NAN } else { 1.0_f16.copysign(self) }
1635 }
1636
1637 /// Returns a number composed of the magnitude of `self` and the sign of
1638 /// `sign`.
1639 ///
1640 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1641 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1642 /// returned.
1643 ///
1644 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1645 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1646 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1647 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1648 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1649 /// info.
1650 ///
1651 /// # Examples
1652 ///
1653 /// ```
1654 /// #![feature(f16)]
1655 /// # #[cfg(target_has_reliable_f16)] {
1656 ///
1657 /// let f = 3.5_f16;
1658 ///
1659 /// assert_eq!(f.copysign(0.42), 3.5_f16);
1660 /// assert_eq!(f.copysign(-0.42), -3.5_f16);
1661 /// assert_eq!((-f).copysign(0.42), 3.5_f16);
1662 /// assert_eq!((-f).copysign(-0.42), -3.5_f16);
1663 ///
1664 /// assert!(f16::NAN.copysign(1.0).is_nan());
1665 /// # }
1666 /// ```
1667 #[inline]
1668 #[unstable(feature = "f16", issue = "116909")]
1669 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1670 #[must_use = "method returns a new number and does not mutate the original value"]
1671 pub const fn copysign(self, sign: f16) -> f16 {
1672 intrinsics::copysignf16(self, sign)
1673 }
1674
1675 /// Float addition that allows optimizations based on algebraic rules.
1676 ///
1677 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1678 #[must_use = "method returns a new number and does not mutate the original value"]
1679 #[unstable(feature = "f16", issue = "116909")]
1680 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1681 #[inline]
1682 pub const fn algebraic_add(self, rhs: f16) -> f16 {
1683 intrinsics::fadd_algebraic(self, rhs)
1684 }
1685
1686 /// Float subtraction that allows optimizations based on algebraic rules.
1687 ///
1688 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1689 #[must_use = "method returns a new number and does not mutate the original value"]
1690 #[unstable(feature = "f16", issue = "116909")]
1691 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1692 #[inline]
1693 pub const fn algebraic_sub(self, rhs: f16) -> f16 {
1694 intrinsics::fsub_algebraic(self, rhs)
1695 }
1696
1697 /// Float multiplication that allows optimizations based on algebraic rules.
1698 ///
1699 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1700 #[must_use = "method returns a new number and does not mutate the original value"]
1701 #[unstable(feature = "f16", issue = "116909")]
1702 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1703 #[inline]
1704 pub const fn algebraic_mul(self, rhs: f16) -> f16 {
1705 intrinsics::fmul_algebraic(self, rhs)
1706 }
1707
1708 /// Float division that allows optimizations based on algebraic rules.
1709 ///
1710 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1711 #[must_use = "method returns a new number and does not mutate the original value"]
1712 #[unstable(feature = "f16", issue = "116909")]
1713 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1714 #[inline]
1715 pub const fn algebraic_div(self, rhs: f16) -> f16 {
1716 intrinsics::fdiv_algebraic(self, rhs)
1717 }
1718
1719 /// Float remainder that allows optimizations based on algebraic rules.
1720 ///
1721 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1722 #[must_use = "method returns a new number and does not mutate the original value"]
1723 #[unstable(feature = "f16", issue = "116909")]
1724 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1725 #[inline]
1726 pub const fn algebraic_rem(self, rhs: f16) -> f16 {
1727 intrinsics::frem_algebraic(self, rhs)
1728 }
1729
1730 /// Returns `self` if the value is not NaN, otherwise returns `replacement`
1731 /// if `self` is NaN.
1732 ///
1733 /// # Examples
1734 ///
1735 /// ```
1736 /// #![feature(f16)]
1737 /// #![feature(float_nan_to)]
1738 /// # #[cfg(target_has_reliable_f16)] {
1739 ///
1740 /// let n = f16::NAN;
1741 /// let x = 2.0f16;
1742 /// let y = f16::INFINITY;
1743 ///
1744 /// assert_eq!(n.nan_to(0.0f16), 0.0f16);
1745 /// assert_eq!(x.nan_to(0.0f16), 2.0f16);
1746 /// assert_eq!(y.nan_to(0.0f16), f16::INFINITY);
1747 /// # }
1748 /// ```
1749 #[must_use = "method returns a new float and does not mutate the original value"]
1750 #[unstable(feature = "float_nan_to", issue = "161248")]
1751 #[rustc_const_unstable(feature = "float_nan_to", issue = "161248")]
1752 #[inline]
1753 pub const fn nan_to(self, replacement: f16) -> f16 {
1754 if self.is_nan() { replacement } else { self }
1755 }
1756}
1757
1758// Functions in this module fall into `core_float_math`
1759// #[unstable(feature = "core_float_math", issue = "137578")]
1760#[cfg(not(test))]
1761#[doc(test(attr(
1762 feature(cfg_target_has_reliable_f16_f128),
1763 expect(internal_features),
1764 allow(unused_features)
1765)))]
1766impl f16 {
1767 /// Returns the largest integer less than or equal to `self`.
1768 ///
1769 /// This function always returns the precise result.
1770 ///
1771 /// # Examples
1772 ///
1773 /// ```
1774 /// #![feature(f16)]
1775 /// # #[cfg(target_has_reliable_f16)] {
1776 ///
1777 /// let f = 3.7_f16;
1778 /// let g = 3.0_f16;
1779 /// let h = -3.7_f16;
1780 ///
1781 /// assert_eq!(f.floor(), 3.0);
1782 /// assert_eq!(g.floor(), 3.0);
1783 /// assert_eq!(h.floor(), -4.0);
1784 /// # }
1785 /// ```
1786 #[inline]
1787 #[rustc_allow_incoherent_impl]
1788 #[unstable(feature = "f16", issue = "116909")]
1789 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1790 #[must_use = "method returns a new number and does not mutate the original value"]
1791 pub const fn floor(self) -> f16 {
1792 intrinsics::floorf16(self)
1793 }
1794
1795 /// Returns the smallest integer greater than or equal to `self`.
1796 ///
1797 /// This function always returns the precise result.
1798 ///
1799 /// # Examples
1800 ///
1801 /// ```
1802 /// #![feature(f16)]
1803 /// # #[cfg(target_has_reliable_f16)] {
1804 ///
1805 /// let f = 3.01_f16;
1806 /// let g = 4.0_f16;
1807 ///
1808 /// assert_eq!(f.ceil(), 4.0);
1809 /// assert_eq!(g.ceil(), 4.0);
1810 /// # }
1811 /// ```
1812 #[inline]
1813 #[doc(alias = "ceiling")]
1814 #[rustc_allow_incoherent_impl]
1815 #[unstable(feature = "f16", issue = "116909")]
1816 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1817 #[must_use = "method returns a new number and does not mutate the original value"]
1818 pub const fn ceil(self) -> f16 {
1819 intrinsics::ceilf16(self)
1820 }
1821
1822 /// Returns the nearest integer to `self`. If a value is half-way between two
1823 /// integers, round away from `0.0`.
1824 ///
1825 /// This function always returns the precise result.
1826 ///
1827 /// # Examples
1828 ///
1829 /// ```
1830 /// #![feature(f16)]
1831 /// # #[cfg(target_has_reliable_f16)] {
1832 ///
1833 /// let f = 3.3_f16;
1834 /// let g = -3.3_f16;
1835 /// let h = -3.7_f16;
1836 /// let i = 3.5_f16;
1837 /// let j = 4.5_f16;
1838 ///
1839 /// assert_eq!(f.round(), 3.0);
1840 /// assert_eq!(g.round(), -3.0);
1841 /// assert_eq!(h.round(), -4.0);
1842 /// assert_eq!(i.round(), 4.0);
1843 /// assert_eq!(j.round(), 5.0);
1844 /// # }
1845 /// ```
1846 #[inline]
1847 #[rustc_allow_incoherent_impl]
1848 #[unstable(feature = "f16", issue = "116909")]
1849 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1850 #[must_use = "method returns a new number and does not mutate the original value"]
1851 pub const fn round(self) -> f16 {
1852 intrinsics::roundf16(self)
1853 }
1854
1855 /// Returns the nearest integer to a number. Rounds half-way cases to the number
1856 /// with an even least significant digit.
1857 ///
1858 /// This function always returns the precise result.
1859 ///
1860 /// # Examples
1861 ///
1862 /// ```
1863 /// #![feature(f16)]
1864 /// # #[cfg(target_has_reliable_f16)] {
1865 ///
1866 /// let f = 3.3_f16;
1867 /// let g = -3.3_f16;
1868 /// let h = 3.5_f16;
1869 /// let i = 4.5_f16;
1870 ///
1871 /// assert_eq!(f.round_ties_even(), 3.0);
1872 /// assert_eq!(g.round_ties_even(), -3.0);
1873 /// assert_eq!(h.round_ties_even(), 4.0);
1874 /// assert_eq!(i.round_ties_even(), 4.0);
1875 /// # }
1876 /// ```
1877 #[inline]
1878 #[rustc_allow_incoherent_impl]
1879 #[unstable(feature = "f16", issue = "116909")]
1880 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1881 #[must_use = "method returns a new number and does not mutate the original value"]
1882 pub const fn round_ties_even(self) -> f16 {
1883 intrinsics::round_ties_even_f16(self)
1884 }
1885
1886 /// Returns the integer part of `self`.
1887 /// This means that non-integer numbers are always truncated towards zero.
1888 ///
1889 /// This function always returns the precise result.
1890 ///
1891 /// # Examples
1892 ///
1893 /// ```
1894 /// #![feature(f16)]
1895 /// # #[cfg(target_has_reliable_f16)] {
1896 ///
1897 /// let f = 3.7_f16;
1898 /// let g = 3.0_f16;
1899 /// let h = -3.7_f16;
1900 ///
1901 /// assert_eq!(f.trunc(), 3.0);
1902 /// assert_eq!(g.trunc(), 3.0);
1903 /// assert_eq!(h.trunc(), -3.0);
1904 /// # }
1905 /// ```
1906 #[inline]
1907 #[doc(alias = "truncate")]
1908 #[rustc_allow_incoherent_impl]
1909 #[unstable(feature = "f16", issue = "116909")]
1910 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1911 #[must_use = "method returns a new number and does not mutate the original value"]
1912 pub const fn trunc(self) -> f16 {
1913 intrinsics::truncf16(self)
1914 }
1915
1916 /// Returns the fractional part of `self`.
1917 ///
1918 /// This function always returns the precise result.
1919 ///
1920 /// # Examples
1921 ///
1922 /// ```
1923 /// #![feature(f16)]
1924 /// # #[cfg(target_has_reliable_f16)] {
1925 ///
1926 /// let x = 3.6_f16;
1927 /// let y = -3.6_f16;
1928 /// let abs_difference_x = (x.fract() - 0.6).abs();
1929 /// let abs_difference_y = (y.fract() - (-0.6)).abs();
1930 ///
1931 /// assert!(abs_difference_x <= f16::EPSILON);
1932 /// assert!(abs_difference_y <= f16::EPSILON);
1933 /// # }
1934 /// ```
1935 #[inline]
1936 #[rustc_allow_incoherent_impl]
1937 #[unstable(feature = "f16", issue = "116909")]
1938 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1939 #[must_use = "method returns a new number and does not mutate the original value"]
1940 pub const fn fract(self) -> f16 {
1941 self - self.trunc()
1942 }
1943
1944 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1945 /// error, yielding a more accurate result than an unfused multiply-add.
1946 ///
1947 /// Using `mul_add` *may* be more performant than an unfused multiply-add if
1948 /// the target architecture has a dedicated `fma` CPU instruction. However,
1949 /// this is not always true, and will be heavily dependant on designing
1950 /// algorithms with specific target hardware in mind.
1951 ///
1952 /// # Precision
1953 ///
1954 /// The result of this operation is guaranteed to be the rounded
1955 /// infinite-precision result. It is specified by IEEE 754 as
1956 /// `fusedMultiplyAdd` and guaranteed not to change.
1957 ///
1958 /// # Examples
1959 ///
1960 /// ```
1961 /// #![feature(f16)]
1962 /// # #[cfg(target_has_reliable_f16)] {
1963 ///
1964 /// let m = 10.0_f16;
1965 /// let x = 4.0_f16;
1966 /// let b = 60.0_f16;
1967 ///
1968 /// assert_eq!(m.mul_add(x, b), 100.0);
1969 /// assert_eq!(m * x + b, 100.0);
1970 ///
1971 /// let one_plus_eps = 1.0_f16 + f16::EPSILON;
1972 /// let one_minus_eps = 1.0_f16 - f16::EPSILON;
1973 /// let minus_one = -1.0_f16;
1974 ///
1975 /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1976 /// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f16::EPSILON * f16::EPSILON);
1977 /// // Different rounding with the non-fused multiply and add.
1978 /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1979 /// # }
1980 /// ```
1981 #[inline]
1982 #[rustc_allow_incoherent_impl]
1983 #[unstable(feature = "f16", issue = "116909")]
1984 #[doc(alias = "fmaf16", alias = "fusedMultiplyAdd")]
1985 #[must_use = "method returns a new number and does not mutate the original value"]
1986 pub const fn mul_add(self, a: f16, b: f16) -> f16 {
1987 intrinsics::fmaf16(self, a, b)
1988 }
1989
1990 /// Calculates Euclidean division, the matching method for `rem_euclid`.
1991 ///
1992 /// This computes the integer `n` such that
1993 /// `self = n * rhs + self.rem_euclid(rhs)`.
1994 /// In other words, the result is `self / rhs` rounded to the integer `n`
1995 /// such that `self >= n * rhs`.
1996 ///
1997 /// # Precision
1998 ///
1999 /// The result of this operation is guaranteed to be the rounded
2000 /// infinite-precision result.
2001 ///
2002 /// # Examples
2003 ///
2004 /// ```
2005 /// #![feature(f16)]
2006 /// # #[cfg(target_has_reliable_f16)] {
2007 ///
2008 /// let a: f16 = 7.0;
2009 /// let b = 4.0;
2010 /// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
2011 /// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
2012 /// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
2013 /// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
2014 /// # }
2015 /// ```
2016 #[inline]
2017 #[rustc_allow_incoherent_impl]
2018 #[unstable(feature = "f16", issue = "116909")]
2019 #[must_use = "method returns a new number and does not mutate the original value"]
2020 pub fn div_euclid(self, rhs: f16) -> f16 {
2021 let q = (self / rhs).trunc();
2022 if self % rhs < 0.0 {
2023 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
2024 }
2025 q
2026 }
2027
2028 /// Calculates the least nonnegative remainder of `self` when
2029 /// divided by `rhs`.
2030 ///
2031 /// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
2032 /// most cases. However, due to a floating point round-off error it can
2033 /// result in `r == rhs.abs()`, violating the mathematical definition, if
2034 /// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
2035 /// This result is not an element of the function's codomain, but it is the
2036 /// closest floating point number in the real numbers and thus fulfills the
2037 /// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
2038 /// approximately.
2039 ///
2040 /// # Precision
2041 ///
2042 /// The result of this operation is guaranteed to be the rounded
2043 /// infinite-precision result.
2044 ///
2045 /// # Examples
2046 ///
2047 /// ```
2048 /// #![feature(f16)]
2049 /// # #[cfg(target_has_reliable_f16)] {
2050 ///
2051 /// let a: f16 = 7.0;
2052 /// let b = 4.0;
2053 /// assert_eq!(a.rem_euclid(b), 3.0);
2054 /// assert_eq!((-a).rem_euclid(b), 1.0);
2055 /// assert_eq!(a.rem_euclid(-b), 3.0);
2056 /// assert_eq!((-a).rem_euclid(-b), 1.0);
2057 /// // limitation due to round-off error
2058 /// assert!((-f16::EPSILON).rem_euclid(3.0) != 0.0);
2059 /// # }
2060 /// ```
2061 #[inline]
2062 #[rustc_allow_incoherent_impl]
2063 #[doc(alias = "modulo", alias = "mod")]
2064 #[unstable(feature = "f16", issue = "116909")]
2065 #[must_use = "method returns a new number and does not mutate the original value"]
2066 pub fn rem_euclid(self, rhs: f16) -> f16 {
2067 let r = self % rhs;
2068 if r < 0.0 { r + rhs.abs() } else { r }
2069 }
2070
2071 /// Raises a number to an integer power.
2072 ///
2073 /// Using this function is generally faster than using `powf`.
2074 /// It might have a different sequence of rounding operations than `powf`,
2075 /// so the results are not guaranteed to agree.
2076 ///
2077 /// Note that this function is special in that it can return non-NaN results for NaN inputs. For
2078 /// example, `f16::powi(f16::NAN, 0)` returns `1.0`. However, if an input is a *signaling*
2079 /// NaN, then the result is non-deterministically either a NaN or the result that the
2080 /// corresponding quiet NaN would produce.
2081 ///
2082 /// # Unspecified precision
2083 ///
2084 /// The precision of this function is non-deterministic. This means it varies by platform,
2085 /// Rust version, and can even differ within the same execution from one invocation to the next.
2086 ///
2087 /// # Examples
2088 ///
2089 /// ```
2090 /// #![feature(f16)]
2091 /// # #[cfg(target_has_reliable_f16_math)] {
2092 ///
2093 /// let x = 2.0_f16;
2094 /// let abs_difference = (x.powi(2) - (x * x)).abs();
2095 /// assert!(abs_difference <= 0.1);
2096 ///
2097 /// assert_eq!(f16::powi(f16::NAN, 0), 1.0);
2098 /// assert_eq!(f16::powi(0.0, 0), 1.0);
2099 /// # }
2100 /// ```
2101 #[inline]
2102 #[rustc_allow_incoherent_impl]
2103 #[unstable(feature = "f16", issue = "116909")]
2104 #[must_use = "method returns a new number and does not mutate the original value"]
2105 pub fn powi(self, n: i32) -> f16 {
2106 intrinsics::powif16(self, n)
2107 }
2108
2109 /// Returns the square root of a number.
2110 ///
2111 /// Returns NaN if `self` is a negative number other than `-0.0`.
2112 ///
2113 /// # Precision
2114 ///
2115 /// The result of this operation is guaranteed to be the rounded
2116 /// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
2117 /// and guaranteed not to change.
2118 ///
2119 /// # Examples
2120 ///
2121 /// ```
2122 /// #![feature(f16)]
2123 /// # #[cfg(target_has_reliable_f16)] {
2124 ///
2125 /// let positive = 4.0_f16;
2126 /// let negative = -4.0_f16;
2127 /// let negative_zero = -0.0_f16;
2128 ///
2129 /// assert_eq!(positive.sqrt(), 2.0);
2130 /// assert!(negative.sqrt().is_nan());
2131 /// assert!(negative_zero.sqrt() == negative_zero);
2132 /// # }
2133 /// ```
2134 #[inline]
2135 #[doc(alias = "squareRoot")]
2136 #[rustc_allow_incoherent_impl]
2137 #[unstable(feature = "f16", issue = "116909")]
2138 #[must_use = "method returns a new number and does not mutate the original value"]
2139 pub fn sqrt(self) -> f16 {
2140 intrinsics::sqrtf16(self)
2141 }
2142
2143 /// Returns the cube root of a number.
2144 ///
2145 /// # Unspecified precision
2146 ///
2147 /// The precision of this function is non-deterministic. This means it varies by platform,
2148 /// Rust version, and can even differ within the same execution from one invocation to the next.
2149 ///
2150 /// This function currently corresponds to the `cbrtf` from libc on Unix
2151 /// and Windows. Note that this might change in the future.
2152 ///
2153 /// # Examples
2154 ///
2155 /// ```
2156 /// #![feature(f16)]
2157 /// # #[cfg(target_has_reliable_f16)] {
2158 ///
2159 /// let x = 8.0f16;
2160 ///
2161 /// // x^(1/3) - 2 == 0
2162 /// let abs_difference = (x.cbrt() - 2.0).abs();
2163 ///
2164 /// assert!(abs_difference <= f16::EPSILON);
2165 /// # }
2166 /// ```
2167 #[inline]
2168 #[rustc_allow_incoherent_impl]
2169 #[unstable(feature = "f16", issue = "116909")]
2170 #[must_use = "method returns a new number and does not mutate the original value"]
2171 pub fn cbrt(self) -> f16 {
2172 libm::cbrtf(self as f32) as f16
2173 }
2174}