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