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 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
40 pub const PHI: f16 = 1.618033988749894848204586834365638118_f16;
41
42 /// The Euler-Mascheroni constant (γ)
43 #[unstable(feature = "f16", issue = "116909")]
44 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
45 pub const EGAMMA: f16 = 0.577215664901532860606512090082402431_f16;
46
47 /// π/2
48 #[unstable(feature = "f16", issue = "116909")]
49 pub const FRAC_PI_2: f16 = 1.57079632679489661923132169163975144_f16;
50
51 /// π/3
52 #[unstable(feature = "f16", issue = "116909")]
53 pub const FRAC_PI_3: f16 = 1.04719755119659774615421446109316763_f16;
54
55 /// π/4
56 #[unstable(feature = "f16", issue = "116909")]
57 pub const FRAC_PI_4: f16 = 0.785398163397448309615660845819875721_f16;
58
59 /// π/6
60 #[unstable(feature = "f16", issue = "116909")]
61 pub const FRAC_PI_6: f16 = 0.52359877559829887307710723054658381_f16;
62
63 /// π/8
64 #[unstable(feature = "f16", issue = "116909")]
65 pub const FRAC_PI_8: f16 = 0.39269908169872415480783042290993786_f16;
66
67 /// 1/π
68 #[unstable(feature = "f16", issue = "116909")]
69 pub const FRAC_1_PI: f16 = 0.318309886183790671537767526745028724_f16;
70
71 /// 1/sqrt(π)
72 #[unstable(feature = "f16", issue = "116909")]
73 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
74 pub const FRAC_1_SQRT_PI: f16 = 0.564189583547756286948079451560772586_f16;
75
76 /// 1/sqrt(2π)
77 #[doc(alias = "FRAC_1_SQRT_TAU")]
78 #[unstable(feature = "f16", issue = "116909")]
79 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
80 pub const FRAC_1_SQRT_2PI: f16 = 0.398942280401432677939946059934381868_f16;
81
82 /// 2/π
83 #[unstable(feature = "f16", issue = "116909")]
84 pub const FRAC_2_PI: f16 = 0.636619772367581343075535053490057448_f16;
85
86 /// 2/sqrt(π)
87 #[unstable(feature = "f16", issue = "116909")]
88 pub const FRAC_2_SQRT_PI: f16 = 1.12837916709551257389615890312154517_f16;
89
90 /// sqrt(2)
91 #[unstable(feature = "f16", issue = "116909")]
92 pub const SQRT_2: f16 = 1.41421356237309504880168872420969808_f16;
93
94 /// 1/sqrt(2)
95 #[unstable(feature = "f16", issue = "116909")]
96 pub const FRAC_1_SQRT_2: f16 = 0.707106781186547524400844362104849039_f16;
97
98 /// sqrt(3)
99 #[unstable(feature = "f16", issue = "116909")]
100 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
101 pub const SQRT_3: f16 = 1.732050807568877293527446341505872367_f16;
102
103 /// 1/sqrt(3)
104 #[unstable(feature = "f16", issue = "116909")]
105 // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
106 pub const FRAC_1_SQRT_3: f16 = 0.577350269189625764509148780501957456_f16;
107
108 /// Euler's number (e)
109 #[unstable(feature = "f16", issue = "116909")]
110 pub const E: f16 = 2.71828182845904523536028747135266250_f16;
111
112 /// log<sub>2</sub>(10)
113 #[unstable(feature = "f16", issue = "116909")]
114 pub const LOG2_10: f16 = 3.32192809488736234787031942948939018_f16;
115
116 /// log<sub>2</sub>(e)
117 #[unstable(feature = "f16", issue = "116909")]
118 pub const LOG2_E: f16 = 1.44269504088896340735992468100189214_f16;
119
120 /// log<sub>10</sub>(2)
121 #[unstable(feature = "f16", issue = "116909")]
122 pub const LOG10_2: f16 = 0.301029995663981195213738894724493027_f16;
123
124 /// log<sub>10</sub>(e)
125 #[unstable(feature = "f16", issue = "116909")]
126 pub const LOG10_E: f16 = 0.434294481903251827651128918916605082_f16;
127
128 /// ln(2)
129 #[unstable(feature = "f16", issue = "116909")]
130 pub const LN_2: f16 = 0.693147180559945309417232121458176568_f16;
131
132 /// ln(10)
133 #[unstable(feature = "f16", issue = "116909")]
134 pub const LN_10: f16 = 2.30258509299404568401799145468436421_f16;
135}
136
137impl f16 {
138 // FIXME(f16_f128): almost all methods in this `impl` are missing examples and a const
139 // implementation. Add these once we can run code on all platforms and have f16/f128 in CTFE.
140
141 /// The radix or base of the internal representation of `f16`.
142 #[unstable(feature = "f16", issue = "116909")]
143 pub const RADIX: u32 = 2;
144
145 /// Number of significant digits in base 2.
146 ///
147 /// Note that the size of the mantissa in the bitwise representation is one
148 /// smaller than this since the leading 1 is not stored explicitly.
149 #[unstable(feature = "f16", issue = "116909")]
150 pub const MANTISSA_DIGITS: u32 = 11;
151
152 /// Approximate number of significant digits in base 10.
153 ///
154 /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
155 /// significant digits can be converted to `f16` and back without loss.
156 ///
157 /// Equal to floor(log<sub>10</sub> 2<sup>[`MANTISSA_DIGITS`] − 1</sup>).
158 ///
159 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
160 #[unstable(feature = "f16", issue = "116909")]
161 pub const DIGITS: u32 = 3;
162
163 /// [Machine epsilon] value for `f16`.
164 ///
165 /// This is the difference between `1.0` and the next larger representable number.
166 ///
167 /// Equal to 2<sup>1 − [`MANTISSA_DIGITS`]</sup>.
168 ///
169 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
170 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
171 #[unstable(feature = "f16", issue = "116909")]
172 #[rustc_diagnostic_item = "f16_epsilon"]
173 pub const EPSILON: f16 = 9.7656e-4_f16;
174
175 /// Smallest finite `f16` value.
176 ///
177 /// Equal to −[`MAX`].
178 ///
179 /// [`MAX`]: f16::MAX
180 #[unstable(feature = "f16", issue = "116909")]
181 pub const MIN: f16 = -6.5504e+4_f16;
182 /// Smallest positive normal `f16` value.
183 ///
184 /// Equal to 2<sup>[`MIN_EXP`] − 1</sup>.
185 ///
186 /// [`MIN_EXP`]: f16::MIN_EXP
187 #[unstable(feature = "f16", issue = "116909")]
188 pub const MIN_POSITIVE: f16 = 6.1035e-5_f16;
189 /// Largest finite `f16` value.
190 ///
191 /// Equal to
192 /// (1 − 2<sup>−[`MANTISSA_DIGITS`]</sup>) 2<sup>[`MAX_EXP`]</sup>.
193 ///
194 /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
195 /// [`MAX_EXP`]: f16::MAX_EXP
196 #[unstable(feature = "f16", issue = "116909")]
197 pub const MAX: f16 = 6.5504e+4_f16;
198
199 /// One greater than the minimum possible *normal* power of 2 exponent
200 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
201 ///
202 /// This corresponds to the exact minimum possible *normal* power of 2 exponent
203 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
204 /// In other words, all normal numbers representable by this type are
205 /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
206 #[unstable(feature = "f16", issue = "116909")]
207 pub const MIN_EXP: i32 = -13;
208 /// One greater than the maximum possible power of 2 exponent
209 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
210 ///
211 /// This corresponds to the exact maximum possible power of 2 exponent
212 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
213 /// In other words, all numbers representable by this type are
214 /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
215 #[unstable(feature = "f16", issue = "116909")]
216 pub const MAX_EXP: i32 = 16;
217
218 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
219 ///
220 /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]).
221 ///
222 /// [`MIN_POSITIVE`]: f16::MIN_POSITIVE
223 #[unstable(feature = "f16", issue = "116909")]
224 pub const MIN_10_EXP: i32 = -4;
225 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
226 ///
227 /// Equal to floor(log<sub>10</sub> [`MAX`]).
228 ///
229 /// [`MAX`]: f16::MAX
230 #[unstable(feature = "f16", issue = "116909")]
231 pub const MAX_10_EXP: i32 = 4;
232
233 /// Not a Number (NaN).
234 ///
235 /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
236 /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
237 /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
238 /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
239 /// info.
240 ///
241 /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
242 /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
243 /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
244 /// The concrete bit pattern may change across Rust versions and target platforms.
245 #[allow(clippy::eq_op)]
246 #[rustc_diagnostic_item = "f16_nan"]
247 #[unstable(feature = "f16", issue = "116909")]
248 pub const NAN: f16 = 0.0_f16 / 0.0_f16;
249
250 /// Infinity (∞).
251 #[unstable(feature = "f16", issue = "116909")]
252 pub const INFINITY: f16 = 1.0_f16 / 0.0_f16;
253
254 /// Negative infinity (−∞).
255 #[unstable(feature = "f16", issue = "116909")]
256 pub const NEG_INFINITY: f16 = -1.0_f16 / 0.0_f16;
257
258 /// Sign bit
259 pub(crate) const SIGN_MASK: u16 = 0x8000;
260
261 /// Exponent mask
262 pub(crate) const EXP_MASK: u16 = 0x7c00;
263
264 /// Mantissa mask
265 pub(crate) const MAN_MASK: u16 = 0x03ff;
266
267 /// Minimum representable positive value (min subnormal)
268 const TINY_BITS: u16 = 0x1;
269
270 /// Minimum representable negative value (min negative subnormal)
271 const NEG_TINY_BITS: u16 = Self::TINY_BITS | Self::SIGN_MASK;
272
273 /// Returns `true` if this value is NaN.
274 ///
275 /// ```
276 /// #![feature(f16)]
277 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
278 ///
279 /// let nan = f16::NAN;
280 /// let f = 7.0_f16;
281 ///
282 /// assert!(nan.is_nan());
283 /// assert!(!f.is_nan());
284 /// # }
285 /// ```
286 #[inline]
287 #[must_use]
288 #[unstable(feature = "f16", issue = "116909")]
289 #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
290 pub const fn is_nan(self) -> bool {
291 self != self
292 }
293
294 /// Returns `true` if this value is positive infinity or negative infinity, and
295 /// `false` otherwise.
296 ///
297 /// ```
298 /// #![feature(f16)]
299 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
300 ///
301 /// let f = 7.0f16;
302 /// let inf = f16::INFINITY;
303 /// let neg_inf = f16::NEG_INFINITY;
304 /// let nan = f16::NAN;
305 ///
306 /// assert!(!f.is_infinite());
307 /// assert!(!nan.is_infinite());
308 ///
309 /// assert!(inf.is_infinite());
310 /// assert!(neg_inf.is_infinite());
311 /// # }
312 /// ```
313 #[inline]
314 #[must_use]
315 #[unstable(feature = "f16", issue = "116909")]
316 pub const fn is_infinite(self) -> bool {
317 (self == f16::INFINITY) | (self == f16::NEG_INFINITY)
318 }
319
320 /// Returns `true` if this number is neither infinite nor NaN.
321 ///
322 /// ```
323 /// #![feature(f16)]
324 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
325 ///
326 /// let f = 7.0f16;
327 /// let inf: f16 = f16::INFINITY;
328 /// let neg_inf: f16 = f16::NEG_INFINITY;
329 /// let nan: f16 = f16::NAN;
330 ///
331 /// assert!(f.is_finite());
332 ///
333 /// assert!(!nan.is_finite());
334 /// assert!(!inf.is_finite());
335 /// assert!(!neg_inf.is_finite());
336 /// # }
337 /// ```
338 #[inline]
339 #[must_use]
340 #[unstable(feature = "f16", issue = "116909")]
341 #[rustc_const_unstable(feature = "f16", issue = "116909")]
342 pub const fn is_finite(self) -> bool {
343 // There's no need to handle NaN separately: if self is NaN,
344 // the comparison is not true, exactly as desired.
345 self.abs() < Self::INFINITY
346 }
347
348 /// Returns `true` if the number is [subnormal].
349 ///
350 /// ```
351 /// #![feature(f16)]
352 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
353 ///
354 /// let min = f16::MIN_POSITIVE; // 6.1035e-5
355 /// let max = f16::MAX;
356 /// let lower_than_min = 1.0e-7_f16;
357 /// let zero = 0.0_f16;
358 ///
359 /// assert!(!min.is_subnormal());
360 /// assert!(!max.is_subnormal());
361 ///
362 /// assert!(!zero.is_subnormal());
363 /// assert!(!f16::NAN.is_subnormal());
364 /// assert!(!f16::INFINITY.is_subnormal());
365 /// // Values between `0` and `min` are Subnormal.
366 /// assert!(lower_than_min.is_subnormal());
367 /// # }
368 /// ```
369 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
370 #[inline]
371 #[must_use]
372 #[unstable(feature = "f16", issue = "116909")]
373 pub const fn is_subnormal(self) -> bool {
374 matches!(self.classify(), FpCategory::Subnormal)
375 }
376
377 /// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
378 ///
379 /// ```
380 /// #![feature(f16)]
381 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
382 ///
383 /// let min = f16::MIN_POSITIVE; // 6.1035e-5
384 /// let max = f16::MAX;
385 /// let lower_than_min = 1.0e-7_f16;
386 /// let zero = 0.0_f16;
387 ///
388 /// assert!(min.is_normal());
389 /// assert!(max.is_normal());
390 ///
391 /// assert!(!zero.is_normal());
392 /// assert!(!f16::NAN.is_normal());
393 /// assert!(!f16::INFINITY.is_normal());
394 /// // Values between `0` and `min` are Subnormal.
395 /// assert!(!lower_than_min.is_normal());
396 /// # }
397 /// ```
398 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
399 #[inline]
400 #[must_use]
401 #[unstable(feature = "f16", issue = "116909")]
402 pub const fn is_normal(self) -> bool {
403 matches!(self.classify(), FpCategory::Normal)
404 }
405
406 /// Returns the floating point category of the number. If only one property
407 /// is going to be tested, it is generally faster to use the specific
408 /// predicate instead.
409 ///
410 /// ```
411 /// #![feature(f16)]
412 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
413 ///
414 /// use std::num::FpCategory;
415 ///
416 /// let num = 12.4_f16;
417 /// let inf = f16::INFINITY;
418 ///
419 /// assert_eq!(num.classify(), FpCategory::Normal);
420 /// assert_eq!(inf.classify(), FpCategory::Infinite);
421 /// # }
422 /// ```
423 #[inline]
424 #[unstable(feature = "f16", issue = "116909")]
425 pub const fn classify(self) -> FpCategory {
426 let b = self.to_bits();
427 match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
428 (0, Self::EXP_MASK) => FpCategory::Infinite,
429 (_, Self::EXP_MASK) => FpCategory::Nan,
430 (0, 0) => FpCategory::Zero,
431 (_, 0) => FpCategory::Subnormal,
432 _ => FpCategory::Normal,
433 }
434 }
435
436 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
437 /// positive sign bit and positive infinity.
438 ///
439 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
440 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
441 /// conserved over arithmetic operations, the result of `is_sign_positive` on
442 /// a NaN might produce an unexpected or non-portable result. See the [specification
443 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
444 /// if you need fully portable behavior (will return `false` for all NaNs).
445 ///
446 /// ```
447 /// #![feature(f16)]
448 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
449 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
450 ///
451 /// let f = 7.0_f16;
452 /// let g = -7.0_f16;
453 ///
454 /// assert!(f.is_sign_positive());
455 /// assert!(!g.is_sign_positive());
456 /// # }
457 /// ```
458 #[inline]
459 #[must_use]
460 #[unstable(feature = "f16", issue = "116909")]
461 pub const fn is_sign_positive(self) -> bool {
462 !self.is_sign_negative()
463 }
464
465 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
466 /// negative sign bit and negative infinity.
467 ///
468 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
469 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
470 /// conserved over arithmetic operations, the result of `is_sign_negative` on
471 /// a NaN might produce an unexpected or non-portable result. See the [specification
472 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
473 /// if you need fully portable behavior (will return `false` for all NaNs).
474 ///
475 /// ```
476 /// #![feature(f16)]
477 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
478 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
479 ///
480 /// let f = 7.0_f16;
481 /// let g = -7.0_f16;
482 ///
483 /// assert!(!f.is_sign_negative());
484 /// assert!(g.is_sign_negative());
485 /// # }
486 /// ```
487 #[inline]
488 #[must_use]
489 #[unstable(feature = "f16", issue = "116909")]
490 pub const fn is_sign_negative(self) -> bool {
491 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
492 // applies to zeros and NaNs as well.
493 // SAFETY: This is just transmuting to get the sign bit, it's fine.
494 (self.to_bits() & (1 << 15)) != 0
495 }
496
497 /// Returns the least number greater than `self`.
498 ///
499 /// Let `TINY` be the smallest representable positive `f16`. Then,
500 /// - if `self.is_nan()`, this returns `self`;
501 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
502 /// - if `self` is `-TINY`, this returns -0.0;
503 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
504 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
505 /// - otherwise the unique least value greater than `self` is returned.
506 ///
507 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
508 /// is finite `x == x.next_up().next_down()` also holds.
509 ///
510 /// ```rust
511 /// #![feature(f16)]
512 /// # // FIXME(f16_f128): ABI issues on MSVC
513 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
514 ///
515 /// // f16::EPSILON is the difference between 1.0 and the next number up.
516 /// assert_eq!(1.0f16.next_up(), 1.0 + f16::EPSILON);
517 /// // But not for most numbers.
518 /// assert!(0.1f16.next_up() < 0.1 + f16::EPSILON);
519 /// assert_eq!(4356f16.next_up(), 4360.0);
520 /// # }
521 /// ```
522 ///
523 /// This operation corresponds to IEEE-754 `nextUp`.
524 ///
525 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
526 /// [`INFINITY`]: Self::INFINITY
527 /// [`MIN`]: Self::MIN
528 /// [`MAX`]: Self::MAX
529 #[inline]
530 #[doc(alias = "nextUp")]
531 #[unstable(feature = "f16", issue = "116909")]
532 pub const fn next_up(self) -> Self {
533 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
534 // denormals to zero. This is in general unsound and unsupported, but here
535 // we do our best to still produce the correct result on such targets.
536 let bits = self.to_bits();
537 if self.is_nan() || bits == Self::INFINITY.to_bits() {
538 return self;
539 }
540
541 let abs = bits & !Self::SIGN_MASK;
542 let next_bits = if abs == 0 {
543 Self::TINY_BITS
544 } else if bits == abs {
545 bits + 1
546 } else {
547 bits - 1
548 };
549 Self::from_bits(next_bits)
550 }
551
552 /// Returns the greatest number less than `self`.
553 ///
554 /// Let `TINY` be the smallest representable positive `f16`. Then,
555 /// - if `self.is_nan()`, this returns `self`;
556 /// - if `self` is [`INFINITY`], this returns [`MAX`];
557 /// - if `self` is `TINY`, this returns 0.0;
558 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
559 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
560 /// - otherwise the unique greatest value less than `self` is returned.
561 ///
562 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
563 /// is finite `x == x.next_down().next_up()` also holds.
564 ///
565 /// ```rust
566 /// #![feature(f16)]
567 /// # // FIXME(f16_f128): ABI issues on MSVC
568 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
569 ///
570 /// let x = 1.0f16;
571 /// // Clamp value into range [0, 1).
572 /// let clamped = x.clamp(0.0, 1.0f16.next_down());
573 /// assert!(clamped < 1.0);
574 /// assert_eq!(clamped.next_up(), 1.0);
575 /// # }
576 /// ```
577 ///
578 /// This operation corresponds to IEEE-754 `nextDown`.
579 ///
580 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
581 /// [`INFINITY`]: Self::INFINITY
582 /// [`MIN`]: Self::MIN
583 /// [`MAX`]: Self::MAX
584 #[inline]
585 #[doc(alias = "nextDown")]
586 #[unstable(feature = "f16", issue = "116909")]
587 pub const fn next_down(self) -> Self {
588 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
589 // denormals to zero. This is in general unsound and unsupported, but here
590 // we do our best to still produce the correct result on such targets.
591 let bits = self.to_bits();
592 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
593 return self;
594 }
595
596 let abs = bits & !Self::SIGN_MASK;
597 let next_bits = if abs == 0 {
598 Self::NEG_TINY_BITS
599 } else if bits == abs {
600 bits - 1
601 } else {
602 bits + 1
603 };
604 Self::from_bits(next_bits)
605 }
606
607 /// Takes the reciprocal (inverse) of a number, `1/x`.
608 ///
609 /// ```
610 /// #![feature(f16)]
611 /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
612 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
613 ///
614 /// let x = 2.0_f16;
615 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
616 ///
617 /// assert!(abs_difference <= f16::EPSILON);
618 /// # }
619 /// ```
620 #[inline]
621 #[unstable(feature = "f16", issue = "116909")]
622 #[must_use = "this returns the result of the operation, without modifying the original"]
623 pub const fn recip(self) -> Self {
624 1.0 / self
625 }
626
627 /// Converts radians to degrees.
628 ///
629 /// # Unspecified precision
630 ///
631 /// The precision of this function is non-deterministic. This means it varies by platform,
632 /// Rust version, and can even differ within the same execution from one invocation to the next.
633 ///
634 /// # Examples
635 ///
636 /// ```
637 /// #![feature(f16)]
638 /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
639 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
640 ///
641 /// let angle = std::f16::consts::PI;
642 ///
643 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
644 /// assert!(abs_difference <= 0.5);
645 /// # }
646 /// ```
647 #[inline]
648 #[unstable(feature = "f16", issue = "116909")]
649 #[must_use = "this returns the result of the operation, without modifying the original"]
650 pub const fn to_degrees(self) -> Self {
651 // Use a literal to avoid double rounding, consts::PI is already rounded,
652 // and dividing would round again.
653 const PIS_IN_180: f16 = 57.2957795130823208767981548141051703_f16;
654 self * PIS_IN_180
655 }
656
657 /// Converts degrees to radians.
658 ///
659 /// # Unspecified precision
660 ///
661 /// The precision of this function is non-deterministic. This means it varies by platform,
662 /// Rust version, and can even differ within the same execution from one invocation to the next.
663 ///
664 /// # Examples
665 ///
666 /// ```
667 /// #![feature(f16)]
668 /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
669 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
670 ///
671 /// let angle = 180.0f16;
672 ///
673 /// let abs_difference = (angle.to_radians() - std::f16::consts::PI).abs();
674 ///
675 /// assert!(abs_difference <= 0.01);
676 /// # }
677 /// ```
678 #[inline]
679 #[unstable(feature = "f16", issue = "116909")]
680 #[must_use = "this returns the result of the operation, without modifying the original"]
681 pub const fn to_radians(self) -> f16 {
682 // Use a literal to avoid double rounding, consts::PI is already rounded,
683 // and dividing would round again.
684 const RADS_PER_DEG: f16 = 0.017453292519943295769236907684886_f16;
685 self * RADS_PER_DEG
686 }
687
688 /// Returns the maximum of the two numbers, ignoring NaN.
689 ///
690 /// If exactly one of the arguments is NaN, then the other argument is returned. If both
691 /// arguments are NaN, the return value is NaN, with the bit pattern picked using the usual
692 /// [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs compare equal (such
693 /// as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
694 ///
695 /// This follows the IEEE 754-2008 semantics for `maxNum`, except for handling of signaling NaNs;
696 /// this function handles all NaNs the same way and avoids `maxNum`'s problems with associativity.
697 /// This also matches the behavior of libm’s `fmax`.
698 ///
699 /// ```
700 /// #![feature(f16)]
701 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
702 ///
703 /// let x = 1.0f16;
704 /// let y = 2.0f16;
705 ///
706 /// assert_eq!(x.max(y), y);
707 /// assert_eq!(x.max(f16::NAN), x);
708 /// # }
709 /// ```
710 #[inline]
711 #[unstable(feature = "f16", issue = "116909")]
712 #[rustc_const_unstable(feature = "f16", issue = "116909")]
713 #[must_use = "this returns the result of the comparison, without modifying either input"]
714 pub const fn max(self, other: f16) -> f16 {
715 intrinsics::maxnumf16(self, other)
716 }
717
718 /// Returns the minimum of the two numbers, ignoring NaN.
719 ///
720 /// If exactly one of the arguments is NaN, then the other argument is returned. If both
721 /// arguments are NaN, the return value is NaN, with the bit pattern picked using the usual
722 /// [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs compare equal (such
723 /// as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
724 ///
725 /// This follows the IEEE 754-2008 semantics for `minNum`, except for handling of signaling NaNs;
726 /// this function handles all NaNs the same way and avoids `minNum`'s problems with associativity.
727 /// This also matches the behavior of libm’s `fmin`.
728 ///
729 /// ```
730 /// #![feature(f16)]
731 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
732 ///
733 /// let x = 1.0f16;
734 /// let y = 2.0f16;
735 ///
736 /// assert_eq!(x.min(y), x);
737 /// assert_eq!(x.min(f16::NAN), x);
738 /// # }
739 /// ```
740 #[inline]
741 #[unstable(feature = "f16", issue = "116909")]
742 #[rustc_const_unstable(feature = "f16", issue = "116909")]
743 #[must_use = "this returns the result of the comparison, without modifying either input"]
744 pub const fn min(self, other: f16) -> f16 {
745 intrinsics::minnumf16(self, other)
746 }
747
748 /// Returns the maximum of the two numbers, propagating NaN.
749 ///
750 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
751 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
752 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
753 /// non-NaN inputs.
754 ///
755 /// This is in contrast to [`f16::max`] which only returns NaN when *both* arguments are NaN,
756 /// and which does not reliably order `-0.0` and `+0.0`.
757 ///
758 /// This follows the IEEE 754-2019 semantics for `maximum`.
759 ///
760 /// ```
761 /// #![feature(f16)]
762 /// #![feature(float_minimum_maximum)]
763 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
764 ///
765 /// let x = 1.0f16;
766 /// let y = 2.0f16;
767 ///
768 /// assert_eq!(x.maximum(y), y);
769 /// assert!(x.maximum(f16::NAN).is_nan());
770 /// # }
771 /// ```
772 #[inline]
773 #[unstable(feature = "f16", issue = "116909")]
774 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
775 #[must_use = "this returns the result of the comparison, without modifying either input"]
776 pub const fn maximum(self, other: f16) -> f16 {
777 intrinsics::maximumf16(self, other)
778 }
779
780 /// Returns the minimum of the two numbers, propagating NaN.
781 ///
782 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
783 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
784 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
785 /// non-NaN inputs.
786 ///
787 /// This is in contrast to [`f16::min`] which only returns NaN when *both* arguments are NaN,
788 /// and which does not reliably order `-0.0` and `+0.0`.
789 ///
790 /// This follows the IEEE 754-2019 semantics for `minimum`.
791 ///
792 /// ```
793 /// #![feature(f16)]
794 /// #![feature(float_minimum_maximum)]
795 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
796 ///
797 /// let x = 1.0f16;
798 /// let y = 2.0f16;
799 ///
800 /// assert_eq!(x.minimum(y), x);
801 /// assert!(x.minimum(f16::NAN).is_nan());
802 /// # }
803 /// ```
804 #[inline]
805 #[unstable(feature = "f16", issue = "116909")]
806 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
807 #[must_use = "this returns the result of the comparison, without modifying either input"]
808 pub const fn minimum(self, other: f16) -> f16 {
809 intrinsics::minimumf16(self, other)
810 }
811
812 /// Calculates the midpoint (average) between `self` and `rhs`.
813 ///
814 /// This returns NaN when *either* argument is NaN or if a combination of
815 /// +inf and -inf is provided as arguments.
816 ///
817 /// # Examples
818 ///
819 /// ```
820 /// #![feature(f16)]
821 /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
822 ///
823 /// assert_eq!(1f16.midpoint(4.0), 2.5);
824 /// assert_eq!((-5.5f16).midpoint(8.0), 1.25);
825 /// # }
826 /// ```
827 #[inline]
828 #[doc(alias = "average")]
829 #[unstable(feature = "f16", issue = "116909")]
830 #[rustc_const_unstable(feature = "f16", issue = "116909")]
831 pub const fn midpoint(self, other: f16) -> f16 {
832 const HI: f16 = f16::MAX / 2.;
833
834 let (a, b) = (self, other);
835 let abs_a = a.abs();
836 let abs_b = b.abs();
837
838 if abs_a <= HI && abs_b <= HI {
839 // Overflow is impossible
840 (a + b) / 2.
841 } else {
842 (a / 2.) + (b / 2.)
843 }
844 }
845
846 /// Rounds toward zero and converts to any primitive integer type,
847 /// assuming that the value is finite and fits in that type.
848 ///
849 /// ```
850 /// #![feature(f16)]
851 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
852 ///
853 /// let value = 4.6_f16;
854 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
855 /// assert_eq!(rounded, 4);
856 ///
857 /// let value = -128.9_f16;
858 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
859 /// assert_eq!(rounded, i8::MIN);
860 /// # }
861 /// ```
862 ///
863 /// # Safety
864 ///
865 /// The value must:
866 ///
867 /// * Not be `NaN`
868 /// * Not be infinite
869 /// * Be representable in the return type `Int`, after truncating off its fractional part
870 #[inline]
871 #[unstable(feature = "f16", issue = "116909")]
872 #[must_use = "this returns the result of the operation, without modifying the original"]
873 pub unsafe fn to_int_unchecked<Int>(self) -> Int
874 where
875 Self: FloatToInt<Int>,
876 {
877 // SAFETY: the caller must uphold the safety contract for
878 // `FloatToInt::to_int_unchecked`.
879 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
880 }
881
882 /// Raw transmutation to `u16`.
883 ///
884 /// This is currently identical to `transmute::<f16, u16>(self)` on all platforms.
885 ///
886 /// See [`from_bits`](#method.from_bits) for some discussion of the
887 /// portability of this operation (there are almost no issues).
888 ///
889 /// Note that this function is distinct from `as` casting, which attempts to
890 /// preserve the *numeric* value, and not the bitwise value.
891 ///
892 /// ```
893 /// #![feature(f16)]
894 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
895 ///
896 /// # // FIXME(f16_f128): enable this once const casting works
897 /// # // assert_ne!((1f16).to_bits(), 1f16 as u128); // to_bits() is not casting!
898 /// assert_eq!((12.5f16).to_bits(), 0x4a40);
899 /// # }
900 /// ```
901 #[inline]
902 #[unstable(feature = "f16", issue = "116909")]
903 #[must_use = "this returns the result of the operation, without modifying the original"]
904 #[allow(unnecessary_transmutes)]
905 pub const fn to_bits(self) -> u16 {
906 // SAFETY: `u16` is a plain old datatype so we can always transmute to it.
907 unsafe { mem::transmute(self) }
908 }
909
910 /// Raw transmutation from `u16`.
911 ///
912 /// This is currently identical to `transmute::<u16, f16>(v)` on all platforms.
913 /// It turns out this is incredibly portable, for two reasons:
914 ///
915 /// * Floats and Ints have the same endianness on all supported platforms.
916 /// * IEEE 754 very precisely specifies the bit layout of floats.
917 ///
918 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
919 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
920 /// (notably x86 and ARM) picked the interpretation that was ultimately
921 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
922 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
923 ///
924 /// Rather than trying to preserve signaling-ness cross-platform, this
925 /// implementation favors preserving the exact bits. This means that
926 /// any payloads encoded in NaNs will be preserved even if the result of
927 /// this method is sent over the network from an x86 machine to a MIPS one.
928 ///
929 /// If the results of this method are only manipulated by the same
930 /// architecture that produced them, then there is no portability concern.
931 ///
932 /// If the input isn't NaN, then there is no portability concern.
933 ///
934 /// If you don't care about signalingness (very likely), then there is no
935 /// portability concern.
936 ///
937 /// Note that this function is distinct from `as` casting, which attempts to
938 /// preserve the *numeric* value, and not the bitwise value.
939 ///
940 /// ```
941 /// #![feature(f16)]
942 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
943 ///
944 /// let v = f16::from_bits(0x4a40);
945 /// assert_eq!(v, 12.5);
946 /// # }
947 /// ```
948 #[inline]
949 #[must_use]
950 #[unstable(feature = "f16", issue = "116909")]
951 #[allow(unnecessary_transmutes)]
952 pub const fn from_bits(v: u16) -> Self {
953 // It turns out the safety issues with sNaN were overblown! Hooray!
954 // SAFETY: `u16` is a plain old datatype so we can always transmute from it.
955 unsafe { mem::transmute(v) }
956 }
957
958 /// Returns the memory representation of this floating point number as a byte array in
959 /// big-endian (network) byte order.
960 ///
961 /// See [`from_bits`](Self::from_bits) for some discussion of the
962 /// portability of this operation (there are almost no issues).
963 ///
964 /// # Examples
965 ///
966 /// ```
967 /// #![feature(f16)]
968 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
969 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
970 ///
971 /// let bytes = 12.5f16.to_be_bytes();
972 /// assert_eq!(bytes, [0x4a, 0x40]);
973 /// # }
974 /// ```
975 #[inline]
976 #[unstable(feature = "f16", issue = "116909")]
977 #[must_use = "this returns the result of the operation, without modifying the original"]
978 pub const fn to_be_bytes(self) -> [u8; 2] {
979 self.to_bits().to_be_bytes()
980 }
981
982 /// Returns the memory representation of this floating point number as a byte array in
983 /// little-endian byte order.
984 ///
985 /// See [`from_bits`](Self::from_bits) for some discussion of the
986 /// portability of this operation (there are almost no issues).
987 ///
988 /// # Examples
989 ///
990 /// ```
991 /// #![feature(f16)]
992 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
993 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
994 ///
995 /// let bytes = 12.5f16.to_le_bytes();
996 /// assert_eq!(bytes, [0x40, 0x4a]);
997 /// # }
998 /// ```
999 #[inline]
1000 #[unstable(feature = "f16", issue = "116909")]
1001 #[must_use = "this returns the result of the operation, without modifying the original"]
1002 pub const fn to_le_bytes(self) -> [u8; 2] {
1003 self.to_bits().to_le_bytes()
1004 }
1005
1006 /// Returns the memory representation of this floating point number as a byte array in
1007 /// native byte order.
1008 ///
1009 /// As the target platform's native endianness is used, portable code
1010 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1011 ///
1012 /// [`to_be_bytes`]: f16::to_be_bytes
1013 /// [`to_le_bytes`]: f16::to_le_bytes
1014 ///
1015 /// See [`from_bits`](Self::from_bits) for some discussion of the
1016 /// portability of this operation (there are almost no issues).
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```
1021 /// #![feature(f16)]
1022 /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
1023 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1024 ///
1025 /// let bytes = 12.5f16.to_ne_bytes();
1026 /// assert_eq!(
1027 /// bytes,
1028 /// if cfg!(target_endian = "big") {
1029 /// [0x4a, 0x40]
1030 /// } else {
1031 /// [0x40, 0x4a]
1032 /// }
1033 /// );
1034 /// # }
1035 /// ```
1036 #[inline]
1037 #[unstable(feature = "f16", issue = "116909")]
1038 #[must_use = "this returns the result of the operation, without modifying the original"]
1039 pub const fn to_ne_bytes(self) -> [u8; 2] {
1040 self.to_bits().to_ne_bytes()
1041 }
1042
1043 /// Creates a floating point value from its representation as a byte array in big endian.
1044 ///
1045 /// See [`from_bits`](Self::from_bits) for some discussion of the
1046 /// portability of this operation (there are almost no issues).
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```
1051 /// #![feature(f16)]
1052 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1053 ///
1054 /// let value = f16::from_be_bytes([0x4a, 0x40]);
1055 /// assert_eq!(value, 12.5);
1056 /// # }
1057 /// ```
1058 #[inline]
1059 #[must_use]
1060 #[unstable(feature = "f16", issue = "116909")]
1061 pub const fn from_be_bytes(bytes: [u8; 2]) -> Self {
1062 Self::from_bits(u16::from_be_bytes(bytes))
1063 }
1064
1065 /// Creates a floating point value from its representation as a byte array in little endian.
1066 ///
1067 /// See [`from_bits`](Self::from_bits) for some discussion of the
1068 /// portability of this operation (there are almost no issues).
1069 ///
1070 /// # Examples
1071 ///
1072 /// ```
1073 /// #![feature(f16)]
1074 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1075 ///
1076 /// let value = f16::from_le_bytes([0x40, 0x4a]);
1077 /// assert_eq!(value, 12.5);
1078 /// # }
1079 /// ```
1080 #[inline]
1081 #[must_use]
1082 #[unstable(feature = "f16", issue = "116909")]
1083 pub const fn from_le_bytes(bytes: [u8; 2]) -> Self {
1084 Self::from_bits(u16::from_le_bytes(bytes))
1085 }
1086
1087 /// Creates a floating point value from its representation as a byte array in native endian.
1088 ///
1089 /// As the target platform's native endianness is used, portable code
1090 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1091 /// appropriate instead.
1092 ///
1093 /// [`from_be_bytes`]: f16::from_be_bytes
1094 /// [`from_le_bytes`]: f16::from_le_bytes
1095 ///
1096 /// See [`from_bits`](Self::from_bits) for some discussion of the
1097 /// portability of this operation (there are almost no issues).
1098 ///
1099 /// # Examples
1100 ///
1101 /// ```
1102 /// #![feature(f16)]
1103 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1104 ///
1105 /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") {
1106 /// [0x4a, 0x40]
1107 /// } else {
1108 /// [0x40, 0x4a]
1109 /// });
1110 /// assert_eq!(value, 12.5);
1111 /// # }
1112 /// ```
1113 #[inline]
1114 #[must_use]
1115 #[unstable(feature = "f16", issue = "116909")]
1116 pub const fn from_ne_bytes(bytes: [u8; 2]) -> Self {
1117 Self::from_bits(u16::from_ne_bytes(bytes))
1118 }
1119
1120 /// Returns the ordering between `self` and `other`.
1121 ///
1122 /// Unlike the standard partial comparison between floating point numbers,
1123 /// this comparison always produces an ordering in accordance to
1124 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1125 /// floating point standard. The values are ordered in the following sequence:
1126 ///
1127 /// - negative quiet NaN
1128 /// - negative signaling NaN
1129 /// - negative infinity
1130 /// - negative numbers
1131 /// - negative subnormal numbers
1132 /// - negative zero
1133 /// - positive zero
1134 /// - positive subnormal numbers
1135 /// - positive numbers
1136 /// - positive infinity
1137 /// - positive signaling NaN
1138 /// - positive quiet NaN.
1139 ///
1140 /// The ordering established by this function does not always agree with the
1141 /// [`PartialOrd`] and [`PartialEq`] implementations of `f16`. For example,
1142 /// they consider negative and positive zero equal, while `total_cmp`
1143 /// doesn't.
1144 ///
1145 /// The interpretation of the signaling NaN bit follows the definition in
1146 /// the IEEE 754 standard, which may not match the interpretation by some of
1147 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1148 ///
1149 /// # Example
1150 ///
1151 /// ```
1152 /// #![feature(f16)]
1153 /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
1154 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1155 ///
1156 /// struct GoodBoy {
1157 /// name: &'static str,
1158 /// weight: f16,
1159 /// }
1160 ///
1161 /// let mut bois = vec![
1162 /// GoodBoy { name: "Pucci", weight: 0.1 },
1163 /// GoodBoy { name: "Woofer", weight: 99.0 },
1164 /// GoodBoy { name: "Yapper", weight: 10.0 },
1165 /// GoodBoy { name: "Chonk", weight: f16::INFINITY },
1166 /// GoodBoy { name: "Abs. Unit", weight: f16::NAN },
1167 /// GoodBoy { name: "Floaty", weight: -5.0 },
1168 /// ];
1169 ///
1170 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1171 ///
1172 /// // `f16::NAN` could be positive or negative, which will affect the sort order.
1173 /// if f16::NAN.is_sign_negative() {
1174 /// bois.into_iter().map(|b| b.weight)
1175 /// .zip([f16::NAN, -5.0, 0.1, 10.0, 99.0, f16::INFINITY].iter())
1176 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1177 /// } else {
1178 /// bois.into_iter().map(|b| b.weight)
1179 /// .zip([-5.0, 0.1, 10.0, 99.0, f16::INFINITY, f16::NAN].iter())
1180 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1181 /// }
1182 /// # }
1183 /// ```
1184 #[inline]
1185 #[must_use]
1186 #[unstable(feature = "f16", issue = "116909")]
1187 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1188 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1189 let mut left = self.to_bits() as i16;
1190 let mut right = other.to_bits() as i16;
1191
1192 // In case of negatives, flip all the bits except the sign
1193 // to achieve a similar layout as two's complement integers
1194 //
1195 // Why does this work? IEEE 754 floats consist of three fields:
1196 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1197 // fields as a whole have the property that their bitwise order is
1198 // equal to the numeric magnitude where the magnitude is defined.
1199 // The magnitude is not normally defined on NaN values, but
1200 // IEEE 754 totalOrder defines the NaN values also to follow the
1201 // bitwise order. This leads to order explained in the doc comment.
1202 // However, the representation of magnitude is the same for negative
1203 // and positive numbers – only the sign bit is different.
1204 // To easily compare the floats as signed integers, we need to
1205 // flip the exponent and mantissa bits in case of negative numbers.
1206 // We effectively convert the numbers to "two's complement" form.
1207 //
1208 // To do the flipping, we construct a mask and XOR against it.
1209 // We branchlessly calculate an "all-ones except for the sign bit"
1210 // mask from negative-signed values: right shifting sign-extends
1211 // the integer, so we "fill" the mask with sign bits, and then
1212 // convert to unsigned to push one more zero bit.
1213 // On positive values, the mask is all zeros, so it's a no-op.
1214 left ^= (((left >> 15) as u16) >> 1) as i16;
1215 right ^= (((right >> 15) as u16) >> 1) as i16;
1216
1217 left.cmp(&right)
1218 }
1219
1220 /// Restrict a value to a certain interval unless it is NaN.
1221 ///
1222 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1223 /// less than `min`. Otherwise this returns `self`.
1224 ///
1225 /// Note that this function returns NaN if the initial value was NaN as
1226 /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1227 /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1228 ///
1229 /// # Panics
1230 ///
1231 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1232 ///
1233 /// # Examples
1234 ///
1235 /// ```
1236 /// #![feature(f16)]
1237 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1238 ///
1239 /// assert!((-3.0f16).clamp(-2.0, 1.0) == -2.0);
1240 /// assert!((0.0f16).clamp(-2.0, 1.0) == 0.0);
1241 /// assert!((2.0f16).clamp(-2.0, 1.0) == 1.0);
1242 /// assert!((f16::NAN).clamp(-2.0, 1.0).is_nan());
1243 ///
1244 /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1245 /// assert!((0.0f16).clamp(-0.0, -0.0) == 0.0);
1246 /// assert!((1.0f16).clamp(-0.0, 0.0) == 0.0);
1247 /// // This is definitely a negative zero.
1248 /// assert!((-1.0f16).clamp(-0.0, 1.0).is_sign_negative());
1249 /// # }
1250 /// ```
1251 #[inline]
1252 #[unstable(feature = "f16", issue = "116909")]
1253 #[must_use = "method returns a new number and does not mutate the original value"]
1254 pub const fn clamp(mut self, min: f16, max: f16) -> f16 {
1255 const_assert!(
1256 min <= max,
1257 "min > max, or either was NaN",
1258 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1259 min: f16,
1260 max: f16,
1261 );
1262
1263 if self < min {
1264 self = min;
1265 }
1266 if self > max {
1267 self = max;
1268 }
1269 self
1270 }
1271
1272 /// Clamps this number to a symmetric range centered around zero.
1273 ///
1274 /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1275 ///
1276 /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1277 /// explicit about the intent.
1278 ///
1279 /// # Panics
1280 ///
1281 /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1282 ///
1283 /// # Examples
1284 ///
1285 /// ```
1286 /// #![feature(f16)]
1287 /// #![feature(clamp_magnitude)]
1288 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1289 /// assert_eq!(5.0f16.clamp_magnitude(3.0), 3.0);
1290 /// assert_eq!((-5.0f16).clamp_magnitude(3.0), -3.0);
1291 /// assert_eq!(2.0f16.clamp_magnitude(3.0), 2.0);
1292 /// assert_eq!((-2.0f16).clamp_magnitude(3.0), -2.0);
1293 /// # }
1294 /// ```
1295 #[inline]
1296 #[unstable(feature = "clamp_magnitude", issue = "148519")]
1297 #[must_use = "this returns the clamped value and does not modify the original"]
1298 pub fn clamp_magnitude(self, limit: f16) -> f16 {
1299 assert!(limit >= 0.0, "limit must be non-negative");
1300 let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1301 self.clamp(-limit, limit)
1302 }
1303
1304 /// Computes the absolute value of `self`.
1305 ///
1306 /// This function always returns the precise result.
1307 ///
1308 /// # Examples
1309 ///
1310 /// ```
1311 /// #![feature(f16)]
1312 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1313 ///
1314 /// let x = 3.5_f16;
1315 /// let y = -3.5_f16;
1316 ///
1317 /// assert_eq!(x.abs(), x);
1318 /// assert_eq!(y.abs(), -y);
1319 ///
1320 /// assert!(f16::NAN.abs().is_nan());
1321 /// # }
1322 /// ```
1323 #[inline]
1324 #[unstable(feature = "f16", issue = "116909")]
1325 #[rustc_const_unstable(feature = "f16", issue = "116909")]
1326 #[must_use = "method returns a new number and does not mutate the original value"]
1327 pub const fn abs(self) -> Self {
1328 // FIXME(f16_f128): replace with `intrinsics::fabsf16` when available
1329 Self::from_bits(self.to_bits() & !(1 << 15))
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(all(target_arch = "x86_64", target_os = "linux"))] {
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(all(target_arch = "x86_64", target_os = "linux"))] {
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_math)] {
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_math)] {
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_math)] {
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_math)] {
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_math)] {
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_math)] {
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_math)] {
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 #[rustc_const_unstable(feature = "const_mul_add", issue = "146724")]
1686 pub const fn mul_add(self, a: f16, b: f16) -> f16 {
1687 intrinsics::fmaf16(self, a, b)
1688 }
1689
1690 /// Calculates Euclidean division, the matching method for `rem_euclid`.
1691 ///
1692 /// This computes the integer `n` such that
1693 /// `self = n * rhs + self.rem_euclid(rhs)`.
1694 /// In other words, the result is `self / rhs` rounded to the integer `n`
1695 /// such that `self >= n * rhs`.
1696 ///
1697 /// # Precision
1698 ///
1699 /// The result of this operation is guaranteed to be the rounded
1700 /// infinite-precision result.
1701 ///
1702 /// # Examples
1703 ///
1704 /// ```
1705 /// #![feature(f16)]
1706 /// # #[cfg(not(miri))]
1707 /// # #[cfg(target_has_reliable_f16_math)] {
1708 ///
1709 /// let a: f16 = 7.0;
1710 /// let b = 4.0;
1711 /// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
1712 /// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
1713 /// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
1714 /// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
1715 /// # }
1716 /// ```
1717 #[inline]
1718 #[rustc_allow_incoherent_impl]
1719 #[unstable(feature = "f16", issue = "116909")]
1720 #[must_use = "method returns a new number and does not mutate the original value"]
1721 pub fn div_euclid(self, rhs: f16) -> f16 {
1722 let q = (self / rhs).trunc();
1723 if self % rhs < 0.0 {
1724 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1725 }
1726 q
1727 }
1728
1729 /// Calculates the least nonnegative remainder of `self (mod 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_math)] {
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_math)] {
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_math)] {
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_math)] {
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}