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