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