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