Debian Codegraph @

third_party/rust/half/src/binary16.rs

raw
1 #[cfg(all(feature = "serde", feature = "alloc"))]
2 #[allow(unused_imports)]
3 use alloc::string::ToString;
4 #[cfg(feature = "bytemuck")]
5 use bytemuck::{Pod, Zeroable};
6 use core::{
7 cmp::Ordering,
8 iter::{Product, Sum},
9 num::FpCategory,
10 ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign},
11 };
12 #[cfg(not(target_arch = "spirv"))]
13 use core::{
14 fmt::{
15 Binary, Debug, Display, Error, Formatter, LowerExp, LowerHex, Octal, UpperExp, UpperHex,
16 },
17 num::ParseFloatError,
18 str::FromStr,
19 };
20 #[cfg(feature = "serde")]
21 use serde::{Deserialize, Serialize};
22 #[cfg(feature = "zerocopy")]
23 use zerocopy::{FromBytes, IntoBytes};
24
25 pub(crate) mod arch;
26
27 /// A 16-bit floating point type implementing the IEEE 754-2008 standard [`binary16`] a.k.a "half"
28 /// format.
29 ///
30 /// This 16-bit floating point type is intended for efficient storage where the full range and
31 /// precision of a larger floating point value is not required.
32 ///
33 /// [`binary16`]: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
34 #[allow(non_camel_case_types)]
35 #[derive(Clone, Copy, Default)]
36 #[repr(transparent)]
37 #[cfg_attr(feature = "serde", derive(Serialize))]
38 #[cfg_attr(
39 feature = "rkyv",
40 derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
41 )]
42 #[cfg_attr(feature = "rkyv", rkyv(resolver = F16Resolver))]
43 #[cfg_attr(feature = "bytemuck", derive(Zeroable, Pod))]
44 #[cfg_attr(feature = "zerocopy", derive(IntoBytes, FromBytes))]
45 #[cfg_attr(kani, derive(kani::Arbitrary))]
46 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
47 pub struct f16(u16);
48
49 impl f16 {
50 /// Constructs a 16-bit floating point value from the raw bits.
51 #[inline]
52 #[must_use]
53 pub const fn from_bits(bits: u16) -> f16 {
54 f16(bits)
55 }
56
57 /// Constructs a 16-bit floating point value from a 32-bit floating point value.
58 ///
59 /// This operation is lossy. If the 32-bit value is to large to fit in 16-bits, ±∞ will result.
60 /// NaN values are preserved. 32-bit subnormal values are too tiny to be represented in 16-bits
61 /// and result in ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit
62 /// subnormals or ±0. All other values are truncated and rounded to the nearest representable
63 /// 16-bit value.
64 #[inline]
65 #[must_use]
66 pub fn from_f32(value: f32) -> f16 {
67 f16(arch::f32_to_f16(value))
68 }
69
70 /// Constructs a 16-bit floating point value from a 32-bit floating point value.
71 ///
72 /// This function is identical to [`from_f32`][Self::from_f32] except it never uses hardware
73 /// intrinsics, which allows it to be `const`. [`from_f32`][Self::from_f32] should be preferred
74 /// in any non-`const` context.
75 ///
76 /// This operation is lossy. If the 32-bit value is to large to fit in 16-bits, ±∞ will result.
77 /// NaN values are preserved. 32-bit subnormal values are too tiny to be represented in 16-bits
78 /// and result in ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit
79 /// subnormals or ±0. All other values are truncated and rounded to the nearest representable
80 /// 16-bit value.
81 #[inline]
82 #[must_use]
83 pub const fn from_f32_const(value: f32) -> f16 {
84 f16(arch::f32_to_f16_fallback(value))
85 }
86
87 /// Constructs a 16-bit floating point value from a 64-bit floating point value.
88 ///
89 /// This operation is lossy. If the 64-bit value is to large to fit in 16-bits, ±∞ will result.
90 /// NaN values are preserved. 64-bit subnormal values are too tiny to be represented in 16-bits
91 /// and result in ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit
92 /// subnormals or ±0. All other values are truncated and rounded to the nearest representable
93 /// 16-bit value.
94 #[inline]
95 #[must_use]
96 pub fn from_f64(value: f64) -> f16 {
97 f16(arch::f64_to_f16(value))
98 }
99
100 /// Constructs a 16-bit floating point value from a 64-bit floating point value.
101 ///
102 /// This function is identical to [`from_f64`][Self::from_f64] except it never uses hardware
103 /// intrinsics, which allows it to be `const`. [`from_f64`][Self::from_f64] should be preferred
104 /// in any non-`const` context.
105 ///
106 /// This operation is lossy. If the 64-bit value is to large to fit in 16-bits, ±∞ will result.
107 /// NaN values are preserved. 64-bit subnormal values are too tiny to be represented in 16-bits
108 /// and result in ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit
109 /// subnormals or ±0. All other values are truncated and rounded to the nearest representable
110 /// 16-bit value.
111 #[inline]
112 #[must_use]
113 pub const fn from_f64_const(value: f64) -> f16 {
114 f16(arch::f64_to_f16_fallback(value))
115 }
116
117 /// Converts a [`struct@f16`] into the underlying bit representation.
118 #[inline]
119 #[must_use]
120 pub const fn to_bits(self) -> u16 {
121 self.0
122 }
123
124 /// Returns the memory representation of the underlying bit representation as a byte array in
125 /// little-endian byte order.
126 ///
127 /// # Examples
128 ///
129 /// ```rust
130 /// # use half::prelude::*;
131 /// let bytes = f16::from_f32(12.5).to_le_bytes();
132 /// assert_eq!(bytes, [0x40, 0x4A]);
133 /// ```
134 #[inline]
135 #[must_use]
136 pub const fn to_le_bytes(self) -> [u8; 2] {
137 self.0.to_le_bytes()
138 }
139
140 /// Returns the memory representation of the underlying bit representation as a byte array in
141 /// big-endian (network) byte order.
142 ///
143 /// # Examples
144 ///
145 /// ```rust
146 /// # use half::prelude::*;
147 /// let bytes = f16::from_f32(12.5).to_be_bytes();
148 /// assert_eq!(bytes, [0x4A, 0x40]);
149 /// ```
150 #[inline]
151 #[must_use]
152 pub const fn to_be_bytes(self) -> [u8; 2] {
153 self.0.to_be_bytes()
154 }
155
156 /// Returns the memory representation of the underlying bit representation as a byte array in
157 /// native byte order.
158 ///
159 /// As the target platform's native endianness is used, portable code should use
160 /// [`to_be_bytes`][Self::to_be_bytes] or [`to_le_bytes`][Self::to_le_bytes], as appropriate,
161 /// instead.
162 ///
163 /// # Examples
164 ///
165 /// ```rust
166 /// # use half::prelude::*;
167 /// let bytes = f16::from_f32(12.5).to_ne_bytes();
168 /// assert_eq!(bytes, if cfg!(target_endian = "big") {
169 /// [0x4A, 0x40]
170 /// } else {
171 /// [0x40, 0x4A]
172 /// });
173 /// ```
174 #[inline]
175 #[must_use]
176 pub const fn to_ne_bytes(self) -> [u8; 2] {
177 self.0.to_ne_bytes()
178 }
179
180 /// Creates a floating point value from its representation as a byte array in little endian.
181 ///
182 /// # Examples
183 ///
184 /// ```rust
185 /// # use half::prelude::*;
186 /// let value = f16::from_le_bytes([0x40, 0x4A]);
187 /// assert_eq!(value, f16::from_f32(12.5));
188 /// ```
189 #[inline]
190 #[must_use]
191 pub const fn from_le_bytes(bytes: [u8; 2]) -> f16 {
192 f16::from_bits(u16::from_le_bytes(bytes))
193 }
194
195 /// Creates a floating point value from its representation as a byte array in big endian.
196 ///
197 /// # Examples
198 ///
199 /// ```rust
200 /// # use half::prelude::*;
201 /// let value = f16::from_be_bytes([0x4A, 0x40]);
202 /// assert_eq!(value, f16::from_f32(12.5));
203 /// ```
204 #[inline]
205 #[must_use]
206 pub const fn from_be_bytes(bytes: [u8; 2]) -> f16 {
207 f16::from_bits(u16::from_be_bytes(bytes))
208 }
209
210 /// Creates a floating point value from its representation as a byte array in native endian.
211 ///
212 /// As the target platform's native endianness is used, portable code likely wants to use
213 /// [`from_be_bytes`][Self::from_be_bytes] or [`from_le_bytes`][Self::from_le_bytes], as
214 /// appropriate instead.
215 ///
216 /// # Examples
217 ///
218 /// ```rust
219 /// # use half::prelude::*;
220 /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") {
221 /// [0x4A, 0x40]
222 /// } else {
223 /// [0x40, 0x4A]
224 /// });
225 /// assert_eq!(value, f16::from_f32(12.5));
226 /// ```
227 #[inline]
228 #[must_use]
229 pub const fn from_ne_bytes(bytes: [u8; 2]) -> f16 {
230 f16::from_bits(u16::from_ne_bytes(bytes))
231 }
232
233 /// Converts a [`struct@f16`] value into a `f32` value.
234 ///
235 /// This conversion is lossless as all 16-bit floating point values can be represented exactly
236 /// in 32-bit floating point.
237 #[inline]
238 #[must_use]
239 pub fn to_f32(self) -> f32 {
240 arch::f16_to_f32(self.0)
241 }
242
243 /// Converts a [`struct@f16`] value into a `f32` value.
244 ///
245 /// This function is identical to [`to_f32`][Self::to_f32] except it never uses hardware
246 /// intrinsics, which allows it to be `const`. [`to_f32`][Self::to_f32] should be preferred
247 /// in any non-`const` context.
248 ///
249 /// This conversion is lossless as all 16-bit floating point values can be represented exactly
250 /// in 32-bit floating point.
251 #[inline]
252 #[must_use]
253 pub const fn to_f32_const(self) -> f32 {
254 arch::f16_to_f32_fallback(self.0)
255 }
256
257 /// Converts a [`struct@f16`] value into a `f64` value.
258 ///
259 /// This conversion is lossless as all 16-bit floating point values can be represented exactly
260 /// in 64-bit floating point.
261 #[inline]
262 #[must_use]
263 pub fn to_f64(self) -> f64 {
264 arch::f16_to_f64(self.0)
265 }
266
267 /// Converts a [`struct@f16`] value into a `f64` value.
268 ///
269 /// This function is identical to [`to_f64`][Self::to_f64] except it never uses hardware
270 /// intrinsics, which allows it to be `const`. [`to_f64`][Self::to_f64] should be preferred
271 /// in any non-`const` context.
272 ///
273 /// This conversion is lossless as all 16-bit floating point values can be represented exactly
274 /// in 64-bit floating point.
275 #[inline]
276 #[must_use]
277 pub const fn to_f64_const(self) -> f64 {
278 arch::f16_to_f64_fallback(self.0)
279 }
280
281 /// Returns `true` if this value is `NaN` and `false` otherwise.
282 ///
283 /// # Examples
284 ///
285 /// ```rust
286 /// # use half::prelude::*;
287 ///
288 /// let nan = f16::NAN;
289 /// let f = f16::from_f32(7.0_f32);
290 ///
291 /// assert!(nan.is_nan());
292 /// assert!(!f.is_nan());
293 /// ```
294 #[inline]
295 #[must_use]
296 pub const fn is_nan(self) -> bool {
297 self.0 & 0x7FFFu16 > 0x7C00u16
298 }
299
300 /// Returns `true` if this value is ±∞ and `false`.
301 /// otherwise.
302 ///
303 /// # Examples
304 ///
305 /// ```rust
306 /// # use half::prelude::*;
307 ///
308 /// let f = f16::from_f32(7.0f32);
309 /// let inf = f16::INFINITY;
310 /// let neg_inf = f16::NEG_INFINITY;
311 /// let nan = f16::NAN;
312 ///
313 /// assert!(!f.is_infinite());
314 /// assert!(!nan.is_infinite());
315 ///
316 /// assert!(inf.is_infinite());
317 /// assert!(neg_inf.is_infinite());
318 /// ```
319 #[inline]
320 #[must_use]
321 pub const fn is_infinite(self) -> bool {
322 self.0 & 0x7FFFu16 == 0x7C00u16
323 }
324
325 /// Returns `true` if this number is neither infinite nor `NaN`.
326 ///
327 /// # Examples
328 ///
329 /// ```rust
330 /// # use half::prelude::*;
331 ///
332 /// let f = f16::from_f32(7.0f32);
333 /// let inf = f16::INFINITY;
334 /// let neg_inf = f16::NEG_INFINITY;
335 /// let nan = f16::NAN;
336 ///
337 /// assert!(f.is_finite());
338 ///
339 /// assert!(!nan.is_finite());
340 /// assert!(!inf.is_finite());
341 /// assert!(!neg_inf.is_finite());
342 /// ```
343 #[inline]
344 #[must_use]
345 pub const fn is_finite(self) -> bool {
346 self.0 & 0x7C00u16 != 0x7C00u16
347 }
348
349 /// Returns `true` if the number is neither zero, infinite, subnormal, or `NaN`.
350 ///
351 /// # Examples
352 ///
353 /// ```rust
354 /// # use half::prelude::*;
355 ///
356 /// let min = f16::MIN_POSITIVE;
357 /// let max = f16::MAX;
358 /// let lower_than_min = f16::from_f32(1.0e-10_f32);
359 /// let zero = f16::from_f32(0.0_f32);
360 ///
361 /// assert!(min.is_normal());
362 /// assert!(max.is_normal());
363 ///
364 /// assert!(!zero.is_normal());
365 /// assert!(!f16::NAN.is_normal());
366 /// assert!(!f16::INFINITY.is_normal());
367 /// // Values between `0` and `min` are Subnormal.
368 /// assert!(!lower_than_min.is_normal());
369 /// ```
370 #[inline]
371 #[must_use]
372 pub const fn is_normal(self) -> bool {
373 let exp = self.0 & 0x7C00u16;
374 exp != 0x7C00u16 && exp != 0
375 }
376
377 /// Returns the floating point category of the number.
378 ///
379 /// If only one property is going to be tested, it is generally faster to use the specific
380 /// predicate instead.
381 ///
382 /// # Examples
383 ///
384 /// ```rust
385 /// use std::num::FpCategory;
386 /// # use half::prelude::*;
387 ///
388 /// let num = f16::from_f32(12.4_f32);
389 /// let inf = f16::INFINITY;
390 ///
391 /// assert_eq!(num.classify(), FpCategory::Normal);
392 /// assert_eq!(inf.classify(), FpCategory::Infinite);
393 /// ```
394 #[must_use]
395 pub const fn classify(self) -> FpCategory {
396 let exp = self.0 & 0x7C00u16;
397 let man = self.0 & 0x03FFu16;
398 match (exp, man) {
399 (0, 0) => FpCategory::Zero,
400 (0, _) => FpCategory::Subnormal,
401 (0x7C00u16, 0) => FpCategory::Infinite,
402 (0x7C00u16, _) => FpCategory::Nan,
403 _ => FpCategory::Normal,
404 }
405 }
406
407 /// Returns a number that represents the sign of `self`.
408 ///
409 /// * `1.0` if the number is positive, `+0.0` or [`INFINITY`][f16::INFINITY]
410 /// * `-1.0` if the number is negative, `-0.0` or [`NEG_INFINITY`][f16::NEG_INFINITY]
411 /// * [`NAN`][f16::NAN] if the number is `NaN`
412 ///
413 /// # Examples
414 ///
415 /// ```rust
416 /// # use half::prelude::*;
417 ///
418 /// let f = f16::from_f32(3.5_f32);
419 ///
420 /// assert_eq!(f.signum(), f16::from_f32(1.0));
421 /// assert_eq!(f16::NEG_INFINITY.signum(), f16::from_f32(-1.0));
422 ///
423 /// assert!(f16::NAN.signum().is_nan());
424 /// ```
425 #[must_use]
426 pub const fn signum(self) -> f16 {
427 if self.is_nan() {
428 self
429 } else if self.0 & 0x8000u16 != 0 {
430 Self::NEG_ONE
431 } else {
432 Self::ONE
433 }
434 }
435
436 /// Returns `true` if and only if `self` has a positive sign, including `+0.0`, `NaNs` with a
437 /// positive sign bit and +∞.
438 ///
439 /// # Examples
440 ///
441 /// ```rust
442 /// # use half::prelude::*;
443 ///
444 /// let nan = f16::NAN;
445 /// let f = f16::from_f32(7.0_f32);
446 /// let g = f16::from_f32(-7.0_f32);
447 ///
448 /// assert!(f.is_sign_positive());
449 /// assert!(!g.is_sign_positive());
450 /// // `NaN` can be either positive or negative
451 /// assert!(nan.is_sign_positive() != nan.is_sign_negative());
452 /// ```
453 #[inline]
454 #[must_use]
455 pub const fn is_sign_positive(self) -> bool {
456 self.0 & 0x8000u16 == 0
457 }
458
459 /// Returns `true` if and only if `self` has a negative sign, including `-0.0`, `NaNs` with a
460 /// negative sign bit and −∞.
461 ///
462 /// # Examples
463 ///
464 /// ```rust
465 /// # use half::prelude::*;
466 ///
467 /// let nan = f16::NAN;
468 /// let f = f16::from_f32(7.0f32);
469 /// let g = f16::from_f32(-7.0f32);
470 ///
471 /// assert!(!f.is_sign_negative());
472 /// assert!(g.is_sign_negative());
473 /// // `NaN` can be either positive or negative
474 /// assert!(nan.is_sign_positive() != nan.is_sign_negative());
475 /// ```
476 #[inline]
477 #[must_use]
478 pub const fn is_sign_negative(self) -> bool {
479 self.0 & 0x8000u16 != 0
480 }
481
482 /// Returns a number composed of the magnitude of `self` and the sign of `sign`.
483 ///
484 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
485 /// If `self` is NaN, then NaN with the sign of `sign` is returned.
486 ///
487 /// # Examples
488 ///
489 /// ```
490 /// # use half::prelude::*;
491 /// let f = f16::from_f32(3.5);
492 ///
493 /// assert_eq!(f.copysign(f16::from_f32(0.42)), f16::from_f32(3.5));
494 /// assert_eq!(f.copysign(f16::from_f32(-0.42)), f16::from_f32(-3.5));
495 /// assert_eq!((-f).copysign(f16::from_f32(0.42)), f16::from_f32(3.5));
496 /// assert_eq!((-f).copysign(f16::from_f32(-0.42)), f16::from_f32(-3.5));
497 ///
498 /// assert!(f16::NAN.copysign(f16::from_f32(1.0)).is_nan());
499 /// ```
500 #[inline]
501 #[must_use]
502 pub const fn copysign(self, sign: f16) -> f16 {
503 f16((sign.0 & 0x8000u16) | (self.0 & 0x7FFFu16))
504 }
505
506 /// Returns the maximum of the two numbers.
507 ///
508 /// If one of the arguments is NaN, then the other argument is returned.
509 ///
510 /// # Examples
511 ///
512 /// ```
513 /// # use half::prelude::*;
514 /// let x = f16::from_f32(1.0);
515 /// let y = f16::from_f32(2.0);
516 ///
517 /// assert_eq!(x.max(y), y);
518 /// ```
519 #[inline]
520 #[must_use]
521 pub fn max(self, other: f16) -> f16 {
522 if other > self && !other.is_nan() {
523 other
524 } else {
525 self
526 }
527 }
528
529 /// Returns the minimum of the two numbers.
530 ///
531 /// If one of the arguments is NaN, then the other argument is returned.
532 ///
533 /// # Examples
534 ///
535 /// ```
536 /// # use half::prelude::*;
537 /// let x = f16::from_f32(1.0);
538 /// let y = f16::from_f32(2.0);
539 ///
540 /// assert_eq!(x.min(y), x);
541 /// ```
542 #[inline]
543 #[must_use]
544 pub fn min(self, other: f16) -> f16 {
545 if other < self && !other.is_nan() {
546 other
547 } else {
548 self
549 }
550 }
551
552 /// Restrict a value to a certain interval unless it is NaN.
553 ///
554 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`.
555 /// Otherwise this returns `self`.
556 ///
557 /// Note that this function returns NaN if the initial value was NaN as well.
558 ///
559 /// # Panics
560 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// # use half::prelude::*;
566 /// assert!(f16::from_f32(-3.0).clamp(f16::from_f32(-2.0), f16::from_f32(1.0)) == f16::from_f32(-2.0));
567 /// assert!(f16::from_f32(0.0).clamp(f16::from_f32(-2.0), f16::from_f32(1.0)) == f16::from_f32(0.0));
568 /// assert!(f16::from_f32(2.0).clamp(f16::from_f32(-2.0), f16::from_f32(1.0)) == f16::from_f32(1.0));
569 /// assert!(f16::NAN.clamp(f16::from_f32(-2.0), f16::from_f32(1.0)).is_nan());
570 /// ```
571 #[inline]
572 #[must_use]
573 pub fn clamp(self, min: f16, max: f16) -> f16 {
574 assert!(min <= max);
575 let mut x = self;
576 if x < min {
577 x = min;
578 }
579 if x > max {
580 x = max;
581 }
582 x
583 }
584
585 /// Returns the ordering between `self` and `other`.
586 ///
587 /// Unlike the standard partial comparison between floating point numbers,
588 /// this comparison always produces an ordering in accordance to
589 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
590 /// floating point standard. The values are ordered in the following sequence:
591 ///
592 /// - negative quiet NaN
593 /// - negative signaling NaN
594 /// - negative infinity
595 /// - negative numbers
596 /// - negative subnormal numbers
597 /// - negative zero
598 /// - positive zero
599 /// - positive subnormal numbers
600 /// - positive numbers
601 /// - positive infinity
602 /// - positive signaling NaN
603 /// - positive quiet NaN.
604 ///
605 /// The ordering established by this function does not always agree with the
606 /// [`PartialOrd`] and [`PartialEq`] implementations of `f16`. For example,
607 /// they consider negative and positive zero equal, while `total_cmp`
608 /// doesn't.
609 ///
610 /// The interpretation of the signaling NaN bit follows the definition in
611 /// the IEEE 754 standard, which may not match the interpretation by some of
612 /// the older, non-conformant (e.g. MIPS) hardware implementations.
613 ///
614 /// # Examples
615 /// ```
616 /// # use half::f16;
617 /// let mut v: Vec<f16> = vec![];
618 /// v.push(f16::ONE);
619 /// v.push(f16::INFINITY);
620 /// v.push(f16::NEG_INFINITY);
621 /// v.push(f16::NAN);
622 /// v.push(f16::MAX_SUBNORMAL);
623 /// v.push(-f16::MAX_SUBNORMAL);
624 /// v.push(f16::ZERO);
625 /// v.push(f16::NEG_ZERO);
626 /// v.push(f16::NEG_ONE);
627 /// v.push(f16::MIN_POSITIVE);
628 ///
629 /// v.sort_by(|a, b| a.total_cmp(&b));
630 ///
631 /// assert!(v
632 /// .into_iter()
633 /// .zip(
634 /// [
635 /// f16::NEG_INFINITY,
636 /// f16::NEG_ONE,
637 /// -f16::MAX_SUBNORMAL,
638 /// f16::NEG_ZERO,
639 /// f16::ZERO,
640 /// f16::MAX_SUBNORMAL,
641 /// f16::MIN_POSITIVE,
642 /// f16::ONE,
643 /// f16::INFINITY,
644 /// f16::NAN
645 /// ]
646 /// .iter()
647 /// )
648 /// .all(|(a, b)| a.to_bits() == b.to_bits()));
649 /// ```
650 // Implementation based on: https://doc.rust-lang.org/std/primitive.f32.html#method.total_cmp
651 #[inline]
652 #[must_use]
653 pub fn total_cmp(&self, other: &Self) -> Ordering {
654 let mut left = self.to_bits() as i16;
655 let mut right = other.to_bits() as i16;
656 left ^= (((left >> 15) as u16) >> 1) as i16;
657 right ^= (((right >> 15) as u16) >> 1) as i16;
658 left.cmp(&right)
659 }
660
661 /// Alternate serialize adapter for serializing as a float.
662 ///
663 /// By default, [`struct@f16`] serializes as a newtype of [`u16`]. This is an alternate serialize
664 /// implementation that serializes as an [`f32`] value. It is designed for use with
665 /// `serialize_with` serde attributes. Deserialization from `f32` values is already supported by
666 /// the default deserialize implementation.
667 ///
668 /// # Examples
669 ///
670 /// A demonstration on how to use this adapater:
671 ///
672 /// ```
673 /// use serde::{Serialize, Deserialize};
674 /// use half::f16;
675 ///
676 /// #[derive(Serialize, Deserialize)]
677 /// struct MyStruct {
678 /// #[serde(serialize_with = "f16::serialize_as_f32")]
679 /// value: f16 // Will be serialized as f32 instead of u16
680 /// }
681 /// ```
682 #[cfg(feature = "serde")]
683 pub fn serialize_as_f32<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
684 serializer.serialize_f32(self.to_f32())
685 }
686
687 /// Alternate serialize adapter for serializing as a string.
688 ///
689 /// By default, [`struct@f16`] serializes as a newtype of [`u16`]. This is an alternate serialize
690 /// implementation that serializes as a string value. It is designed for use with
691 /// `serialize_with` serde attributes. Deserialization from string values is already supported
692 /// by the default deserialize implementation.
693 ///
694 /// # Examples
695 ///
696 /// A demonstration on how to use this adapater:
697 ///
698 /// ```
699 /// use serde::{Serialize, Deserialize};
700 /// use half::f16;
701 ///
702 /// #[derive(Serialize, Deserialize)]
703 /// struct MyStruct {
704 /// #[serde(serialize_with = "f16::serialize_as_string")]
705 /// value: f16 // Will be serialized as a string instead of u16
706 /// }
707 /// ```
708 #[cfg(all(feature = "serde", feature = "alloc"))]
709 pub fn serialize_as_string<S: serde::Serializer>(
710 &self,
711 serializer: S,
712 ) -> Result<S::Ok, S::Error> {
713 serializer.serialize_str(&self.to_string())
714 }
715
716 /// Approximate number of [`struct@f16`] significant digits in base 10
717 pub const DIGITS: u32 = 3;
718 /// [`struct@f16`]
719 /// [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value
720 ///
721 /// This is the difference between 1.0 and the next largest representable number.
722 pub const EPSILON: f16 = f16(0x1400u16);
723 /// [`struct@f16`] positive Infinity (+∞)
724 pub const INFINITY: f16 = f16(0x7C00u16);
725 /// Number of [`struct@f16`] significant digits in base 2
726 pub const MANTISSA_DIGITS: u32 = 11;
727 /// Largest finite [`struct@f16`] value
728 pub const MAX: f16 = f16(0x7BFF);
729 /// Maximum possible [`struct@f16`] power of 10 exponent
730 pub const MAX_10_EXP: i32 = 4;
731 /// Maximum possible [`struct@f16`] power of 2 exponent
732 pub const MAX_EXP: i32 = 16;
733 /// Smallest finite [`struct@f16`] value
734 pub const MIN: f16 = f16(0xFBFF);
735 /// Minimum possible normal [`struct@f16`] power of 10 exponent
736 pub const MIN_10_EXP: i32 = -4;
737 /// One greater than the minimum possible normal [`struct@f16`] power of 2 exponent
738 pub const MIN_EXP: i32 = -13;
739 /// Smallest positive normal [`struct@f16`] value
740 pub const MIN_POSITIVE: f16 = f16(0x0400u16);
741 /// [`struct@f16`] Not a Number (NaN)
742 pub const NAN: f16 = f16(0x7E00u16);
743 /// [`struct@f16`] negative infinity (-∞)
744 pub const NEG_INFINITY: f16 = f16(0xFC00u16);
745 /// The radix or base of the internal representation of [`struct@f16`]
746 pub const RADIX: u32 = 2;
747
748 /// Minimum positive subnormal [`struct@f16`] value
749 pub const MIN_POSITIVE_SUBNORMAL: f16 = f16(0x0001u16);
750 /// Maximum subnormal [`struct@f16`] value
751 pub const MAX_SUBNORMAL: f16 = f16(0x03FFu16);
752
753 /// [`struct@f16`] 1
754 pub const ONE: f16 = f16(0x3C00u16);
755 /// [`struct@f16`] 0
756 pub const ZERO: f16 = f16(0x0000u16);
757 /// [`struct@f16`] -0
758 pub const NEG_ZERO: f16 = f16(0x8000u16);
759 /// [`struct@f16`] -1
760 pub const NEG_ONE: f16 = f16(0xBC00u16);
761
762 /// [`struct@f16`] Euler's number (ℯ)
763 pub const E: f16 = f16(0x4170u16);
764 /// [`struct@f16`] Archimedes' constant (π)
765 pub const PI: f16 = f16(0x4248u16);
766 /// [`struct@f16`] 1/π
767 pub const FRAC_1_PI: f16 = f16(0x3518u16);
768 /// [`struct@f16`] 1/√2
769 pub const FRAC_1_SQRT_2: f16 = f16(0x39A8u16);
770 /// [`struct@f16`] 2/π
771 pub const FRAC_2_PI: f16 = f16(0x3918u16);
772 /// [`struct@f16`] 2/√π
773 pub const FRAC_2_SQRT_PI: f16 = f16(0x3C83u16);
774 /// [`struct@f16`] π/2
775 pub const FRAC_PI_2: f16 = f16(0x3E48u16);
776 /// [`struct@f16`] π/3
777 pub const FRAC_PI_3: f16 = f16(0x3C30u16);
778 /// [`struct@f16`] π/4
779 pub const FRAC_PI_4: f16 = f16(0x3A48u16);
780 /// [`struct@f16`] π/6
781 pub const FRAC_PI_6: f16 = f16(0x3830u16);
782 /// [`struct@f16`] π/8
783 pub const FRAC_PI_8: f16 = f16(0x3648u16);
784 /// [`struct@f16`] 𝗅𝗇 10
785 pub const LN_10: f16 = f16(0x409Bu16);
786 /// [`struct@f16`] 𝗅𝗇 2
787 pub const LN_2: f16 = f16(0x398Cu16);
788 /// [`struct@f16`] 𝗅𝗈𝗀₁₀ℯ
789 pub const LOG10_E: f16 = f16(0x36F3u16);
790 /// [`struct@f16`] 𝗅𝗈𝗀₁₀2
791 pub const LOG10_2: f16 = f16(0x34D1u16);
792 /// [`struct@f16`] 𝗅𝗈𝗀₂ℯ
793 pub const LOG2_E: f16 = f16(0x3DC5u16);
794 /// [`struct@f16`] 𝗅𝗈𝗀₂10
795 pub const LOG2_10: f16 = f16(0x42A5u16);
796 /// [`struct@f16`] √2
797 pub const SQRT_2: f16 = f16(0x3DA8u16);
798 }
799
800 impl From<f16> for f32 {
801 #[inline]
802 fn from(x: f16) -> f32 {
803 x.to_f32()
804 }
805 }
806
807 impl From<f16> for f64 {
808 #[inline]
809 fn from(x: f16) -> f64 {
810 x.to_f64()
811 }
812 }
813
814 impl From<i8> for f16 {
815 #[inline]
816 fn from(x: i8) -> f16 {
817 // Convert to f32, then to f16
818 f16::from_f32(f32::from(x))
819 }
820 }
821
822 impl From<u8> for f16 {
823 #[inline]
824 fn from(x: u8) -> f16 {
825 // Convert to f32, then to f16
826 f16::from_f32(f32::from(x))
827 }
828 }
829
830 impl PartialEq for f16 {
831 fn eq(&self, other: &f16) -> bool {
832 if self.is_nan() || other.is_nan() {
833 false
834 } else {
835 (self.0 == other.0) || ((self.0 | other.0) & 0x7FFFu16 == 0)
836 }
837 }
838 }
839
840 impl PartialOrd for f16 {
841 fn partial_cmp(&self, other: &f16) -> Option<Ordering> {
842 if self.is_nan() || other.is_nan() {
843 None
844 } else {
845 let neg = self.0 & 0x8000u16 != 0;
846 let other_neg = other.0 & 0x8000u16 != 0;
847 match (neg, other_neg) {
848 (false, false) => Some(self.0.cmp(&other.0)),
849 (false, true) => {
850 if (self.0 | other.0) & 0x7FFFu16 == 0 {
851 Some(Ordering::Equal)
852 } else {
853 Some(Ordering::Greater)
854 }
855 }
856 (true, false) => {
857 if (self.0 | other.0) & 0x7FFFu16 == 0 {
858 Some(Ordering::Equal)
859 } else {
860 Some(Ordering::Less)
861 }
862 }
863 (true, true) => Some(other.0.cmp(&self.0)),
864 }
865 }
866 }
867
868 fn lt(&self, other: &f16) -> bool {
869 if self.is_nan() || other.is_nan() {
870 false
871 } else {
872 let neg = self.0 & 0x8000u16 != 0;
873 let other_neg = other.0 & 0x8000u16 != 0;
874 match (neg, other_neg) {
875 (false, false) => self.0 < other.0,
876 (false, true) => false,
877 (true, false) => (self.0 | other.0) & 0x7FFFu16 != 0,
878 (true, true) => self.0 > other.0,
879 }
880 }
881 }
882
883 fn le(&self, other: &f16) -> bool {
884 if self.is_nan() || other.is_nan() {
885 false
886 } else {
887 let neg = self.0 & 0x8000u16 != 0;
888 let other_neg = other.0 & 0x8000u16 != 0;
889 match (neg, other_neg) {
890 (false, false) => self.0 <= other.0,
891 (false, true) => (self.0 | other.0) & 0x7FFFu16 == 0,
892 (true, false) => true,
893 (true, true) => self.0 >= other.0,
894 }
895 }
896 }
897
898 fn gt(&self, other: &f16) -> bool {
899 if self.is_nan() || other.is_nan() {
900 false
901 } else {
902 let neg = self.0 & 0x8000u16 != 0;
903 let other_neg = other.0 & 0x8000u16 != 0;
904 match (neg, other_neg) {
905 (false, false) => self.0 > other.0,
906 (false, true) => (self.0 | other.0) & 0x7FFFu16 != 0,
907 (true, false) => false,
908 (true, true) => self.0 < other.0,
909 }
910 }
911 }
912
913 fn ge(&self, other: &f16) -> bool {
914 if self.is_nan() || other.is_nan() {
915 false
916 } else {
917 let neg = self.0 & 0x8000u16 != 0;
918 let other_neg = other.0 & 0x8000u16 != 0;
919 match (neg, other_neg) {
920 (false, false) => self.0 >= other.0,
921 (false, true) => true,
922 (true, false) => (self.0 | other.0) & 0x7FFFu16 == 0,
923 (true, true) => self.0 <= other.0,
924 }
925 }
926 }
927 }
928
929 #[cfg(not(target_arch = "spirv"))]
930 impl FromStr for f16 {
931 type Err = ParseFloatError;
932 fn from_str(src: &str) -> Result<f16, ParseFloatError> {
933 f32::from_str(src).map(f16::from_f32)
934 }
935 }
936
937 #[cfg(not(target_arch = "spirv"))]
938 impl Debug for f16 {
939 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
940 Debug::fmt(&self.to_f32(), f)
941 }
942 }
943
944 #[cfg(not(target_arch = "spirv"))]
945 impl Display for f16 {
946 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
947 Display::fmt(&self.to_f32(), f)
948 }
949 }
950
951 #[cfg(not(target_arch = "spirv"))]
952 impl LowerExp for f16 {
953 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
954 write!(f, "{:e}", self.to_f32())
955 }
956 }
957
958 #[cfg(not(target_arch = "spirv"))]
959 impl UpperExp for f16 {
960 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
961 write!(f, "{:E}", self.to_f32())
962 }
963 }
964
965 #[cfg(not(target_arch = "spirv"))]
966 impl Binary for f16 {
967 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
968 write!(f, "{:b}", self.0)
969 }
970 }
971
972 #[cfg(not(target_arch = "spirv"))]
973 impl Octal for f16 {
974 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
975 write!(f, "{:o}", self.0)
976 }
977 }
978
979 #[cfg(not(target_arch = "spirv"))]
980 impl LowerHex for f16 {
981 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
982 write!(f, "{:x}", self.0)
983 }
984 }
985
986 #[cfg(not(target_arch = "spirv"))]
987 impl UpperHex for f16 {
988 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
989 write!(f, "{:X}", self.0)
990 }
991 }
992
993 impl Neg for f16 {
994 type Output = Self;
995
996 #[inline]
997 fn neg(self) -> Self::Output {
998 Self(self.0 ^ 0x8000)
999 }
1000 }
1001
1002 impl Neg for &f16 {
1003 type Output = <f16 as Neg>::Output;
1004
1005 #[inline]
1006 fn neg(self) -> Self::Output {
1007 Neg::neg(*self)
1008 }
1009 }
1010
1011 impl Add for f16 {
1012 type Output = Self;
1013
1014 #[inline]
1015 fn add(self, rhs: Self) -> Self::Output {
1016 f16(arch::add_f16(self.0, rhs.0))
1017 }
1018 }
1019
1020 impl Add<&f16> for f16 {
1021 type Output = <f16 as Add<f16>>::Output;
1022
1023 #[inline]
1024 fn add(self, rhs: &f16) -> Self::Output {
1025 self.add(*rhs)
1026 }
1027 }
1028
1029 impl Add<&f16> for &f16 {
1030 type Output = <f16 as Add<f16>>::Output;
1031
1032 #[inline]
1033 fn add(self, rhs: &f16) -> Self::Output {
1034 (*self).add(*rhs)
1035 }
1036 }
1037
1038 impl Add<f16> for &f16 {
1039 type Output = <f16 as Add<f16>>::Output;
1040
1041 #[inline]
1042 fn add(self, rhs: f16) -> Self::Output {
1043 (*self).add(rhs)
1044 }
1045 }
1046
1047 impl AddAssign for f16 {
1048 #[inline]
1049 fn add_assign(&mut self, rhs: Self) {
1050 *self = (*self).add(rhs);
1051 }
1052 }
1053
1054 impl AddAssign<&f16> for f16 {
1055 #[inline]
1056 fn add_assign(&mut self, rhs: &f16) {
1057 *self = (*self).add(rhs);
1058 }
1059 }
1060
1061 impl Sub for f16 {
1062 type Output = Self;
1063
1064 #[inline]
1065 fn sub(self, rhs: Self) -> Self::Output {
1066 f16(arch::subtract_f16(self.0, rhs.0))
1067 }
1068 }
1069
1070 impl Sub<&f16> for f16 {
1071 type Output = <f16 as Sub<f16>>::Output;
1072
1073 #[inline]
1074 fn sub(self, rhs: &f16) -> Self::Output {
1075 self.sub(*rhs)
1076 }
1077 }
1078
1079 impl Sub<&f16> for &f16 {
1080 type Output = <f16 as Sub<f16>>::Output;
1081
1082 #[inline]
1083 fn sub(self, rhs: &f16) -> Self::Output {
1084 (*self).sub(*rhs)
1085 }
1086 }
1087
1088 impl Sub<f16> for &f16 {
1089 type Output = <f16 as Sub<f16>>::Output;
1090
1091 #[inline]
1092 fn sub(self, rhs: f16) -> Self::Output {
1093 (*self).sub(rhs)
1094 }
1095 }
1096
1097 impl SubAssign for f16 {
1098 #[inline]
1099 fn sub_assign(&mut self, rhs: Self) {
1100 *self = (*self).sub(rhs);
1101 }
1102 }
1103
1104 impl SubAssign<&f16> for f16 {
1105 #[inline]
1106 fn sub_assign(&mut self, rhs: &f16) {
1107 *self = (*self).sub(rhs);
1108 }
1109 }
1110
1111 impl Mul for f16 {
1112 type Output = Self;
1113
1114 #[inline]
1115 fn mul(self, rhs: Self) -> Self::Output {
1116 f16(arch::multiply_f16(self.0, rhs.0))
1117 }
1118 }
1119
1120 impl Mul<&f16> for f16 {
1121 type Output = <f16 as Mul<f16>>::Output;
1122
1123 #[inline]
1124 fn mul(self, rhs: &f16) -> Self::Output {
1125 self.mul(*rhs)
1126 }
1127 }
1128
1129 impl Mul<&f16> for &f16 {
1130 type Output = <f16 as Mul<f16>>::Output;
1131
1132 #[inline]
1133 fn mul(self, rhs: &f16) -> Self::Output {
1134 (*self).mul(*rhs)
1135 }
1136 }
1137
1138 impl Mul<f16> for &f16 {
1139 type Output = <f16 as Mul<f16>>::Output;
1140
1141 #[inline]
1142 fn mul(self, rhs: f16) -> Self::Output {
1143 (*self).mul(rhs)
1144 }
1145 }
1146
1147 impl MulAssign for f16 {
1148 #[inline]
1149 fn mul_assign(&mut self, rhs: Self) {
1150 *self = (*self).mul(rhs);
1151 }
1152 }
1153
1154 impl MulAssign<&f16> for f16 {
1155 #[inline]
1156 fn mul_assign(&mut self, rhs: &f16) {
1157 *self = (*self).mul(rhs);
1158 }
1159 }
1160
1161 impl Div for f16 {
1162 type Output = Self;
1163
1164 #[inline]
1165 fn div(self, rhs: Self) -> Self::Output {
1166 f16(arch::divide_f16(self.0, rhs.0))
1167 }
1168 }
1169
1170 impl Div<&f16> for f16 {
1171 type Output = <f16 as Div<f16>>::Output;
1172
1173 #[inline]
1174 fn div(self, rhs: &f16) -> Self::Output {
1175 self.div(*rhs)
1176 }
1177 }
1178
1179 impl Div<&f16> for &f16 {
1180 type Output = <f16 as Div<f16>>::Output;
1181
1182 #[inline]
1183 fn div(self, rhs: &f16) -> Self::Output {
1184 (*self).div(*rhs)
1185 }
1186 }
1187
1188 impl Div<f16> for &f16 {
1189 type Output = <f16 as Div<f16>>::Output;
1190
1191 #[inline]
1192 fn div(self, rhs: f16) -> Self::Output {
1193 (*self).div(rhs)
1194 }
1195 }
1196
1197 impl DivAssign for f16 {
1198 #[inline]
1199 fn div_assign(&mut self, rhs: Self) {
1200 *self = (*self).div(rhs);
1201 }
1202 }
1203
1204 impl DivAssign<&f16> for f16 {
1205 #[inline]
1206 fn div_assign(&mut self, rhs: &f16) {
1207 *self = (*self).div(rhs);
1208 }
1209 }
1210
1211 impl Rem for f16 {
1212 type Output = Self;
1213
1214 #[inline]
1215 fn rem(self, rhs: Self) -> Self::Output {
1216 f16(arch::remainder_f16(self.0, rhs.0))
1217 }
1218 }
1219
1220 impl Rem<&f16> for f16 {
1221 type Output = <f16 as Rem<f16>>::Output;
1222
1223 #[inline]
1224 fn rem(self, rhs: &f16) -> Self::Output {
1225 self.rem(*rhs)
1226 }
1227 }
1228
1229 impl Rem<&f16> for &f16 {
1230 type Output = <f16 as Rem<f16>>::Output;
1231
1232 #[inline]
1233 fn rem(self, rhs: &f16) -> Self::Output {
1234 (*self).rem(*rhs)
1235 }
1236 }
1237
1238 impl Rem<f16> for &f16 {
1239 type Output = <f16 as Rem<f16>>::Output;
1240
1241 #[inline]
1242 fn rem(self, rhs: f16) -> Self::Output {
1243 (*self).rem(rhs)
1244 }
1245 }
1246
1247 impl RemAssign for f16 {
1248 #[inline]
1249 fn rem_assign(&mut self, rhs: Self) {
1250 *self = (*self).rem(rhs);
1251 }
1252 }
1253
1254 impl RemAssign<&f16> for f16 {
1255 #[inline]
1256 fn rem_assign(&mut self, rhs: &f16) {
1257 *self = (*self).rem(rhs);
1258 }
1259 }
1260
1261 impl Product for f16 {
1262 #[inline]
1263 fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
1264 f16(arch::product_f16(iter.map(|f| f.to_bits())))
1265 }
1266 }
1267
1268 impl<'a> Product<&'a f16> for f16 {
1269 #[inline]
1270 fn product<I: Iterator<Item = &'a f16>>(iter: I) -> Self {
1271 f16(arch::product_f16(iter.map(|f| f.to_bits())))
1272 }
1273 }
1274
1275 impl Sum for f16 {
1276 #[inline]
1277 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1278 f16(arch::sum_f16(iter.map(|f| f.to_bits())))
1279 }
1280 }
1281
1282 impl<'a> Sum<&'a f16> for f16 {
1283 #[inline]
1284 fn sum<I: Iterator<Item = &'a f16>>(iter: I) -> Self {
1285 f16(arch::sum_f16(iter.map(|f| f.to_bits())))
1286 }
1287 }
1288
1289 #[cfg(feature = "serde")]
1290 struct Visitor;
1291
1292 #[cfg(feature = "serde")]
1293 impl<'de> Deserialize<'de> for f16 {
1294 fn deserialize<D>(deserializer: D) -> Result<f16, D::Error>
1295 where
1296 D: serde::de::Deserializer<'de>,
1297 {
1298 deserializer.deserialize_newtype_struct("f16", Visitor)
1299 }
1300 }
1301
1302 #[cfg(feature = "serde")]
1303 impl<'de> serde::de::Visitor<'de> for Visitor {
1304 type Value = f16;
1305
1306 fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
1307 write!(formatter, "tuple struct f16")
1308 }
1309
1310 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1311 where
1312 D: serde::Deserializer<'de>,
1313 {
1314 Ok(f16(<u16 as Deserialize>::deserialize(deserializer)?))
1315 }
1316
1317 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1318 where
1319 E: serde::de::Error,
1320 {
1321 v.parse().map_err(|_| {
1322 serde::de::Error::invalid_value(serde::de::Unexpected::Str(v), &"a float string")
1323 })
1324 }
1325
1326 fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
1327 where
1328 E: serde::de::Error,
1329 {
1330 Ok(f16::from_f32(v))
1331 }
1332
1333 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
1334 where
1335 E: serde::de::Error,
1336 {
1337 Ok(f16::from_f64(v))
1338 }
1339 }
1340
1341 #[allow(
1342 clippy::cognitive_complexity,
1343 clippy::float_cmp,
1344 clippy::neg_cmp_op_on_partial_ord
1345 )]
1346 #[cfg(test)]
1347 mod test {
1348 use super::*;
1349 #[allow(unused_imports)]
1350 use core::cmp::Ordering;
1351 #[cfg(feature = "num-traits")]
1352 use num_traits::{AsPrimitive, FromBytes, FromPrimitive, ToBytes, ToPrimitive};
1353 use quickcheck_macros::quickcheck;
1354
1355 #[cfg(feature = "num-traits")]
1356 #[test]
1357 fn as_primitive() {
1358 let two = f16::from_f32(2.0);
1359 assert_eq!(<i32 as AsPrimitive<f16>>::as_(2), two);
1360 assert_eq!(<f16 as AsPrimitive<i32>>::as_(two), 2);
1361
1362 assert_eq!(<f32 as AsPrimitive<f16>>::as_(2.0), two);
1363 assert_eq!(<f16 as AsPrimitive<f32>>::as_(two), 2.0);
1364
1365 assert_eq!(<f64 as AsPrimitive<f16>>::as_(2.0), two);
1366 assert_eq!(<f16 as AsPrimitive<f64>>::as_(two), 2.0);
1367 }
1368
1369 #[cfg(feature = "num-traits")]
1370 #[test]
1371 fn to_primitive() {
1372 let two = f16::from_f32(2.0);
1373 assert_eq!(ToPrimitive::to_i32(&two).unwrap(), 2i32);
1374 assert_eq!(ToPrimitive::to_f32(&two).unwrap(), 2.0f32);
1375 assert_eq!(ToPrimitive::to_f64(&two).unwrap(), 2.0f64);
1376 }
1377
1378 #[cfg(feature = "num-traits")]
1379 #[test]
1380 fn from_primitive() {
1381 let two = f16::from_f32(2.0);
1382 assert_eq!(<f16 as FromPrimitive>::from_i32(2).unwrap(), two);
1383 assert_eq!(<f16 as FromPrimitive>::from_f32(2.0).unwrap(), two);
1384 assert_eq!(<f16 as FromPrimitive>::from_f64(2.0).unwrap(), two);
1385 }
1386
1387 #[cfg(feature = "num-traits")]
1388 #[test]
1389 fn to_and_from_bytes() {
1390 let two = f16::from_f32(2.0);
1391 assert_eq!(<f16 as ToBytes>::to_le_bytes(&two), [0, 64]);
1392 assert_eq!(<f16 as FromBytes>::from_le_bytes(&[0, 64]), two);
1393 assert_eq!(<f16 as ToBytes>::to_be_bytes(&two), [64, 0]);
1394 assert_eq!(<f16 as FromBytes>::from_be_bytes(&[64, 0]), two);
1395 }
1396
1397 #[test]
1398 fn test_f16_consts() {
1399 // DIGITS
1400 let digits = ((f16::MANTISSA_DIGITS as f32 - 1.0) * 2f32.log10()).floor() as u32;
1401 assert_eq!(f16::DIGITS, digits);
1402 // sanity check to show test is good
1403 let digits32 = ((core::f32::MANTISSA_DIGITS as f32 - 1.0) * 2f32.log10()).floor() as u32;
1404 assert_eq!(core::f32::DIGITS, digits32);
1405
1406 // EPSILON
1407 let one = f16::from_f32(1.0);
1408 let one_plus_epsilon = f16::from_bits(one.to_bits() + 1);
1409 let epsilon = f16::from_f32(one_plus_epsilon.to_f32() - 1.0);
1410 assert_eq!(f16::EPSILON, epsilon);
1411 // sanity check to show test is good
1412 let one_plus_epsilon32 = f32::from_bits(1.0f32.to_bits() + 1);
1413 let epsilon32 = one_plus_epsilon32 - 1f32;
1414 assert_eq!(core::f32::EPSILON, epsilon32);
1415
1416 // MAX, MIN and MIN_POSITIVE
1417 let max = f16::from_bits(f16::INFINITY.to_bits() - 1);
1418 let min = f16::from_bits(f16::NEG_INFINITY.to_bits() - 1);
1419 let min_pos = f16::from_f32(2f32.powi(f16::MIN_EXP - 1));
1420 assert_eq!(f16::MAX, max);
1421 assert_eq!(f16::MIN, min);
1422 assert_eq!(f16::MIN_POSITIVE, min_pos);
1423 // sanity check to show test is good
1424 let max32 = f32::from_bits(core::f32::INFINITY.to_bits() - 1);
1425 let min32 = f32::from_bits(core::f32::NEG_INFINITY.to_bits() - 1);
1426 let min_pos32 = 2f32.powi(core::f32::MIN_EXP - 1);
1427 assert_eq!(core::f32::MAX, max32);
1428 assert_eq!(core::f32::MIN, min32);
1429 assert_eq!(core::f32::MIN_POSITIVE, min_pos32);
1430
1431 // MIN_10_EXP and MAX_10_EXP
1432 let ten_to_min = 10f32.powi(f16::MIN_10_EXP);
1433 assert!(ten_to_min / 10.0 < f16::MIN_POSITIVE.to_f32());
1434 assert!(ten_to_min > f16::MIN_POSITIVE.to_f32());
1435 let ten_to_max = 10f32.powi(f16::MAX_10_EXP);
1436 assert!(ten_to_max < f16::MAX.to_f32());
1437 assert!(ten_to_max * 10.0 > f16::MAX.to_f32());
1438 // sanity check to show test is good
1439 let ten_to_min32 = 10f64.powi(core::f32::MIN_10_EXP);
1440 assert!(ten_to_min32 / 10.0 < f64::from(core::f32::MIN_POSITIVE));
1441 assert!(ten_to_min32 > f64::from(core::f32::MIN_POSITIVE));
1442 let ten_to_max32 = 10f64.powi(core::f32::MAX_10_EXP);
1443 assert!(ten_to_max32 < f64::from(core::f32::MAX));
1444 assert!(ten_to_max32 * 10.0 > f64::from(core::f32::MAX));
1445 }
1446
1447 #[test]
1448 fn test_f16_consts_from_f32() {
1449 let one = f16::from_f32(1.0);
1450 let zero = f16::from_f32(0.0);
1451 let neg_zero = f16::from_f32(-0.0);
1452 let neg_one = f16::from_f32(-1.0);
1453 let inf = f16::from_f32(core::f32::INFINITY);
1454 let neg_inf = f16::from_f32(core::f32::NEG_INFINITY);
1455 let nan = f16::from_f32(core::f32::NAN);
1456
1457 assert_eq!(f16::ONE, one);
1458 assert_eq!(f16::ZERO, zero);
1459 assert!(zero.is_sign_positive());
1460 assert_eq!(f16::NEG_ZERO, neg_zero);
1461 assert!(neg_zero.is_sign_negative());
1462 assert_eq!(f16::NEG_ONE, neg_one);
1463 assert!(neg_one.is_sign_negative());
1464 assert_eq!(f16::INFINITY, inf);
1465 assert_eq!(f16::NEG_INFINITY, neg_inf);
1466 assert!(nan.is_nan());
1467 assert!(f16::NAN.is_nan());
1468
1469 let e = f16::from_f32(core::f32::consts::E);
1470 let pi = f16::from_f32(core::f32::consts::PI);
1471 let frac_1_pi = f16::from_f32(core::f32::consts::FRAC_1_PI);
1472 let frac_1_sqrt_2 = f16::from_f32(core::f32::consts::FRAC_1_SQRT_2);
1473 let frac_2_pi = f16::from_f32(core::f32::consts::FRAC_2_PI);
1474 let frac_2_sqrt_pi = f16::from_f32(core::f32::consts::FRAC_2_SQRT_PI);
1475 let frac_pi_2 = f16::from_f32(core::f32::consts::FRAC_PI_2);
1476 let frac_pi_3 = f16::from_f32(core::f32::consts::FRAC_PI_3);
1477 let frac_pi_4 = f16::from_f32(core::f32::consts::FRAC_PI_4);
1478 let frac_pi_6 = f16::from_f32(core::f32::consts::FRAC_PI_6);
1479 let frac_pi_8 = f16::from_f32(core::f32::consts::FRAC_PI_8);
1480 let ln_10 = f16::from_f32(core::f32::consts::LN_10);
1481 let ln_2 = f16::from_f32(core::f32::consts::LN_2);
1482 let log10_e = f16::from_f32(core::f32::consts::LOG10_E);
1483 // core::f32::consts::LOG10_2 requires rustc 1.43.0
1484 let log10_2 = f16::from_f32(2f32.log10());
1485 let log2_e = f16::from_f32(core::f32::consts::LOG2_E);
1486 // core::f32::consts::LOG2_10 requires rustc 1.43.0
1487 let log2_10 = f16::from_f32(10f32.log2());
1488 let sqrt_2 = f16::from_f32(core::f32::consts::SQRT_2);
1489
1490 assert_eq!(f16::E, e);
1491 assert_eq!(f16::PI, pi);
1492 assert_eq!(f16::FRAC_1_PI, frac_1_pi);
1493 assert_eq!(f16::FRAC_1_SQRT_2, frac_1_sqrt_2);
1494 assert_eq!(f16::FRAC_2_PI, frac_2_pi);
1495 assert_eq!(f16::FRAC_2_SQRT_PI, frac_2_sqrt_pi);
1496 assert_eq!(f16::FRAC_PI_2, frac_pi_2);
1497 assert_eq!(f16::FRAC_PI_3, frac_pi_3);
1498 assert_eq!(f16::FRAC_PI_4, frac_pi_4);
1499 assert_eq!(f16::FRAC_PI_6, frac_pi_6);
1500 assert_eq!(f16::FRAC_PI_8, frac_pi_8);
1501 assert_eq!(f16::LN_10, ln_10);
1502 assert_eq!(f16::LN_2, ln_2);
1503 assert_eq!(f16::LOG10_E, log10_e);
1504 assert_eq!(f16::LOG10_2, log10_2);
1505 assert_eq!(f16::LOG2_E, log2_e);
1506 assert_eq!(f16::LOG2_10, log2_10);
1507 assert_eq!(f16::SQRT_2, sqrt_2);
1508 }
1509
1510 #[test]
1511 fn test_f16_consts_from_f64() {
1512 let one = f16::from_f64(1.0);
1513 let zero = f16::from_f64(0.0);
1514 let neg_zero = f16::from_f64(-0.0);
1515 let inf = f16::from_f64(core::f64::INFINITY);
1516 let neg_inf = f16::from_f64(core::f64::NEG_INFINITY);
1517 let nan = f16::from_f64(core::f64::NAN);
1518
1519 assert_eq!(f16::ONE, one);
1520 assert_eq!(f16::ZERO, zero);
1521 assert!(zero.is_sign_positive());
1522 assert_eq!(f16::NEG_ZERO, neg_zero);
1523 assert!(neg_zero.is_sign_negative());
1524 assert_eq!(f16::INFINITY, inf);
1525 assert_eq!(f16::NEG_INFINITY, neg_inf);
1526 assert!(nan.is_nan());
1527 assert!(f16::NAN.is_nan());
1528
1529 let e = f16::from_f64(core::f64::consts::E);
1530 let pi = f16::from_f64(core::f64::consts::PI);
1531 let frac_1_pi = f16::from_f64(core::f64::consts::FRAC_1_PI);
1532 let frac_1_sqrt_2 = f16::from_f64(core::f64::consts::FRAC_1_SQRT_2);
1533 let frac_2_pi = f16::from_f64(core::f64::consts::FRAC_2_PI);
1534 let frac_2_sqrt_pi = f16::from_f64(core::f64::consts::FRAC_2_SQRT_PI);
1535 let frac_pi_2 = f16::from_f64(core::f64::consts::FRAC_PI_2);
1536 let frac_pi_3 = f16::from_f64(core::f64::consts::FRAC_PI_3);
1537 let frac_pi_4 = f16::from_f64(core::f64::consts::FRAC_PI_4);
1538 let frac_pi_6 = f16::from_f64(core::f64::consts::FRAC_PI_6);
1539 let frac_pi_8 = f16::from_f64(core::f64::consts::FRAC_PI_8);
1540 let ln_10 = f16::from_f64(core::f64::consts::LN_10);
1541 let ln_2 = f16::from_f64(core::f64::consts::LN_2);
1542 let log10_e = f16::from_f64(core::f64::consts::LOG10_E);
1543 // core::f64::consts::LOG10_2 requires rustc 1.43.0
1544 let log10_2 = f16::from_f64(2f64.log10());
1545 let log2_e = f16::from_f64(core::f64::consts::LOG2_E);
1546 // core::f64::consts::LOG2_10 requires rustc 1.43.0
1547 let log2_10 = f16::from_f64(10f64.log2());
1548 let sqrt_2 = f16::from_f64(core::f64::consts::SQRT_2);
1549
1550 assert_eq!(f16::E, e);
1551 assert_eq!(f16::PI, pi);
1552 assert_eq!(f16::FRAC_1_PI, frac_1_pi);
1553 assert_eq!(f16::FRAC_1_SQRT_2, frac_1_sqrt_2);
1554 assert_eq!(f16::FRAC_2_PI, frac_2_pi);
1555 assert_eq!(f16::FRAC_2_SQRT_PI, frac_2_sqrt_pi);
1556 assert_eq!(f16::FRAC_PI_2, frac_pi_2);
1557 assert_eq!(f16::FRAC_PI_3, frac_pi_3);
1558 assert_eq!(f16::FRAC_PI_4, frac_pi_4);
1559 assert_eq!(f16::FRAC_PI_6, frac_pi_6);
1560 assert_eq!(f16::FRAC_PI_8, frac_pi_8);
1561 assert_eq!(f16::LN_10, ln_10);
1562 assert_eq!(f16::LN_2, ln_2);
1563 assert_eq!(f16::LOG10_E, log10_e);
1564 assert_eq!(f16::LOG10_2, log10_2);
1565 assert_eq!(f16::LOG2_E, log2_e);
1566 assert_eq!(f16::LOG2_10, log2_10);
1567 assert_eq!(f16::SQRT_2, sqrt_2);
1568 }
1569
1570 #[test]
1571 fn test_nan_conversion_to_smaller() {
1572 let nan64 = f64::from_bits(0x7FF0_0000_0000_0001u64);
1573 let neg_nan64 = f64::from_bits(0xFFF0_0000_0000_0001u64);
1574 let nan32 = f32::from_bits(0x7F80_0001u32);
1575 let neg_nan32 = f32::from_bits(0xFF80_0001u32);
1576 let nan32_from_64 = nan64 as f32;
1577 let neg_nan32_from_64 = neg_nan64 as f32;
1578 let nan16_from_64 = f16::from_f64(nan64);
1579 let neg_nan16_from_64 = f16::from_f64(neg_nan64);
1580 let nan16_from_32 = f16::from_f32(nan32);
1581 let neg_nan16_from_32 = f16::from_f32(neg_nan32);
1582
1583 assert!(nan64.is_nan() && nan64.is_sign_positive());
1584 assert!(neg_nan64.is_nan() && neg_nan64.is_sign_negative());
1585 assert!(nan32.is_nan() && nan32.is_sign_positive());
1586 assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative());
1587
1588 // f32/f64 NaN conversion sign is non-deterministic: https://github.com/starkat99/half-rs/issues/103
1589 assert!(nan32_from_64.is_nan());
1590 assert!(neg_nan32_from_64.is_nan());
1591 assert!(nan16_from_64.is_nan());
1592 assert!(neg_nan16_from_64.is_nan());
1593 assert!(nan16_from_32.is_nan());
1594 assert!(neg_nan16_from_32.is_nan());
1595 }
1596
1597 #[test]
1598 fn test_nan_conversion_to_larger() {
1599 let nan16 = f16::from_bits(0x7C01u16);
1600 let neg_nan16 = f16::from_bits(0xFC01u16);
1601 let nan32 = f32::from_bits(0x7F80_0001u32);
1602 let neg_nan32 = f32::from_bits(0xFF80_0001u32);
1603 let nan32_from_16 = f32::from(nan16);
1604 let neg_nan32_from_16 = f32::from(neg_nan16);
1605 let nan64_from_16 = f64::from(nan16);
1606 let neg_nan64_from_16 = f64::from(neg_nan16);
1607 let nan64_from_32 = f64::from(nan32);
1608 let neg_nan64_from_32 = f64::from(neg_nan32);
1609
1610 assert!(nan16.is_nan() && nan16.is_sign_positive());
1611 assert!(neg_nan16.is_nan() && neg_nan16.is_sign_negative());
1612 assert!(nan32.is_nan() && nan32.is_sign_positive());
1613 assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative());
1614
1615 // f32/f64 NaN conversion sign is non-deterministic: https://github.com/starkat99/half-rs/issues/103
1616 assert!(nan32_from_16.is_nan());
1617 assert!(neg_nan32_from_16.is_nan());
1618 assert!(nan64_from_16.is_nan());
1619 assert!(neg_nan64_from_16.is_nan());
1620 assert!(nan64_from_32.is_nan());
1621 assert!(neg_nan64_from_32.is_nan());
1622 }
1623
1624 #[test]
1625 fn test_f16_to_f32() {
1626 let f = f16::from_f32(7.0);
1627 assert_eq!(f.to_f32(), 7.0f32);
1628
1629 // 7.1 is NOT exactly representable in 16-bit, it's rounded
1630 let f = f16::from_f32(7.1);
1631 let diff = (f.to_f32() - 7.1f32).abs();
1632 // diff must be <= 4 * EPSILON, as 7 has two more significant bits than 1
1633 assert!(diff <= 4.0 * f16::EPSILON.to_f32());
1634
1635 assert_eq!(f16::from_bits(0x0000_0001).to_f32(), 2.0f32.powi(-24));
1636 assert_eq!(f16::from_bits(0x0000_0005).to_f32(), 5.0 * 2.0f32.powi(-24));
1637
1638 assert_eq!(f16::from_bits(0x0000_0001), f16::from_f32(2.0f32.powi(-24)));
1639 assert_eq!(
1640 f16::from_bits(0x0000_0005),
1641 f16::from_f32(5.0 * 2.0f32.powi(-24))
1642 );
1643 }
1644
1645 #[test]
1646 fn test_f16_to_f64() {
1647 let f = f16::from_f64(7.0);
1648 assert_eq!(f.to_f64(), 7.0f64);
1649
1650 // 7.1 is NOT exactly representable in 16-bit, it's rounded
1651 let f = f16::from_f64(7.1);
1652 let diff = (f.to_f64() - 7.1f64).abs();
1653 // diff must be <= 4 * EPSILON, as 7 has two more significant bits than 1
1654 assert!(diff <= 4.0 * f16::EPSILON.to_f64());
1655
1656 assert_eq!(f16::from_bits(0x0000_0001).to_f64(), 2.0f64.powi(-24));
1657 assert_eq!(f16::from_bits(0x0000_0005).to_f64(), 5.0 * 2.0f64.powi(-24));
1658
1659 assert_eq!(f16::from_bits(0x0000_0001), f16::from_f64(2.0f64.powi(-24)));
1660 assert_eq!(
1661 f16::from_bits(0x0000_0005),
1662 f16::from_f64(5.0 * 2.0f64.powi(-24))
1663 );
1664 }
1665
1666 #[test]
1667 fn test_comparisons() {
1668 let zero = f16::from_f64(0.0);
1669 let one = f16::from_f64(1.0);
1670 let neg_zero = f16::from_f64(-0.0);
1671 let neg_one = f16::from_f64(-1.0);
1672
1673 assert_eq!(zero.partial_cmp(&neg_zero), Some(Ordering::Equal));
1674 assert_eq!(neg_zero.partial_cmp(&zero), Some(Ordering::Equal));
1675 assert!(zero == neg_zero);
1676 assert!(neg_zero == zero);
1677 assert!(!(zero != neg_zero));
1678 assert!(!(neg_zero != zero));
1679 assert!(!(zero < neg_zero));
1680 assert!(!(neg_zero < zero));
1681 assert!(zero <= neg_zero);
1682 assert!(neg_zero <= zero);
1683 assert!(!(zero > neg_zero));
1684 assert!(!(neg_zero > zero));
1685 assert!(zero >= neg_zero);
1686 assert!(neg_zero >= zero);
1687
1688 assert_eq!(one.partial_cmp(&neg_zero), Some(Ordering::Greater));
1689 assert_eq!(neg_zero.partial_cmp(&one), Some(Ordering::Less));
1690 assert!(!(one == neg_zero));
1691 assert!(!(neg_zero == one));
1692 assert!(one != neg_zero);
1693 assert!(neg_zero != one);
1694 assert!(!(one < neg_zero));
1695 assert!(neg_zero < one);
1696 assert!(!(one <= neg_zero));
1697 assert!(neg_zero <= one);
1698 assert!(one > neg_zero);
1699 assert!(!(neg_zero > one));
1700 assert!(one >= neg_zero);
1701 assert!(!(neg_zero >= one));
1702
1703 assert_eq!(one.partial_cmp(&neg_one), Some(Ordering::Greater));
1704 assert_eq!(neg_one.partial_cmp(&one), Some(Ordering::Less));
1705 assert!(!(one == neg_one));
1706 assert!(!(neg_one == one));
1707 assert!(one != neg_one);
1708 assert!(neg_one != one);
1709 assert!(!(one < neg_one));
1710 assert!(neg_one < one);
1711 assert!(!(one <= neg_one));
1712 assert!(neg_one <= one);
1713 assert!(one > neg_one);
1714 assert!(!(neg_one > one));
1715 assert!(one >= neg_one);
1716 assert!(!(neg_one >= one));
1717 }
1718
1719 #[test]
1720 #[allow(clippy::erasing_op, clippy::identity_op)]
1721 fn round_to_even_f32() {
1722 // smallest positive subnormal = 0b0.0000_0000_01 * 2^-14 = 2^-24
1723 let min_sub = f16::from_bits(1);
1724 let min_sub_f = (-24f32).exp2();
1725 assert_eq!(f16::from_f32(min_sub_f).to_bits(), min_sub.to_bits());
1726 assert_eq!(f32::from(min_sub).to_bits(), min_sub_f.to_bits());
1727
1728 // 0.0000000000_011111 rounded to 0.0000000000 (< tie, no rounding)
1729 // 0.0000000000_100000 rounded to 0.0000000000 (tie and even, remains at even)
1730 // 0.0000000000_100001 rounded to 0.0000000001 (> tie, rounds up)
1731 assert_eq!(
1732 f16::from_f32(min_sub_f * 0.49).to_bits(),
1733 min_sub.to_bits() * 0
1734 );
1735 assert_eq!(
1736 f16::from_f32(min_sub_f * 0.50).to_bits(),
1737 min_sub.to_bits() * 0
1738 );
1739 assert_eq!(
1740 f16::from_f32(min_sub_f * 0.51).to_bits(),
1741 min_sub.to_bits() * 1
1742 );
1743
1744 // 0.0000000001_011111 rounded to 0.0000000001 (< tie, no rounding)
1745 // 0.0000000001_100000 rounded to 0.0000000010 (tie and odd, rounds up to even)
1746 // 0.0000000001_100001 rounded to 0.0000000010 (> tie, rounds up)
1747 assert_eq!(
1748 f16::from_f32(min_sub_f * 1.49).to_bits(),
1749 min_sub.to_bits() * 1
1750 );
1751 assert_eq!(
1752 f16::from_f32(min_sub_f * 1.50).to_bits(),
1753 min_sub.to_bits() * 2
1754 );
1755 assert_eq!(
1756 f16::from_f32(min_sub_f * 1.51).to_bits(),
1757 min_sub.to_bits() * 2
1758 );
1759
1760 // 0.0000000010_011111 rounded to 0.0000000010 (< tie, no rounding)
1761 // 0.0000000010_100000 rounded to 0.0000000010 (tie and even, remains at even)
1762 // 0.0000000010_100001 rounded to 0.0000000011 (> tie, rounds up)
1763 assert_eq!(
1764 f16::from_f32(min_sub_f * 2.49).to_bits(),
1765 min_sub.to_bits() * 2
1766 );
1767 assert_eq!(
1768 f16::from_f32(min_sub_f * 2.50).to_bits(),
1769 min_sub.to_bits() * 2
1770 );
1771 assert_eq!(
1772 f16::from_f32(min_sub_f * 2.51).to_bits(),
1773 min_sub.to_bits() * 3
1774 );
1775
1776 assert_eq!(
1777 f16::from_f32(2000.49f32).to_bits(),
1778 f16::from_f32(2000.0).to_bits()
1779 );
1780 assert_eq!(
1781 f16::from_f32(2000.50f32).to_bits(),
1782 f16::from_f32(2000.0).to_bits()
1783 );
1784 assert_eq!(
1785 f16::from_f32(2000.51f32).to_bits(),
1786 f16::from_f32(2001.0).to_bits()
1787 );
1788 assert_eq!(
1789 f16::from_f32(2001.49f32).to_bits(),
1790 f16::from_f32(2001.0).to_bits()
1791 );
1792 assert_eq!(
1793 f16::from_f32(2001.50f32).to_bits(),
1794 f16::from_f32(2002.0).to_bits()
1795 );
1796 assert_eq!(
1797 f16::from_f32(2001.51f32).to_bits(),
1798 f16::from_f32(2002.0).to_bits()
1799 );
1800 assert_eq!(
1801 f16::from_f32(2002.49f32).to_bits(),
1802 f16::from_f32(2002.0).to_bits()
1803 );
1804 assert_eq!(
1805 f16::from_f32(2002.50f32).to_bits(),
1806 f16::from_f32(2002.0).to_bits()
1807 );
1808 assert_eq!(
1809 f16::from_f32(2002.51f32).to_bits(),
1810 f16::from_f32(2003.0).to_bits()
1811 );
1812 }
1813
1814 #[test]
1815 #[allow(clippy::erasing_op, clippy::identity_op)]
1816 fn round_to_even_f64() {
1817 // smallest positive subnormal = 0b0.0000_0000_01 * 2^-14 = 2^-24
1818 let min_sub = f16::from_bits(1);
1819 let min_sub_f = (-24f64).exp2();
1820 assert_eq!(f16::from_f64(min_sub_f).to_bits(), min_sub.to_bits());
1821 assert_eq!(f64::from(min_sub).to_bits(), min_sub_f.to_bits());
1822
1823 // 0.0000000000_011111 rounded to 0.0000000000 (< tie, no rounding)
1824 // 0.0000000000_100000 rounded to 0.0000000000 (tie and even, remains at even)
1825 // 0.0000000000_100001 rounded to 0.0000000001 (> tie, rounds up)
1826 assert_eq!(
1827 f16::from_f64(min_sub_f * 0.49).to_bits(),
1828 min_sub.to_bits() * 0
1829 );
1830 assert_eq!(
1831 f16::from_f64(min_sub_f * 0.50).to_bits(),
1832 min_sub.to_bits() * 0
1833 );
1834 assert_eq!(
1835 f16::from_f64(min_sub_f * 0.51).to_bits(),
1836 min_sub.to_bits() * 1
1837 );
1838
1839 // 0.0000000001_011111 rounded to 0.0000000001 (< tie, no rounding)
1840 // 0.0000000001_100000 rounded to 0.0000000010 (tie and odd, rounds up to even)
1841 // 0.0000000001_100001 rounded to 0.0000000010 (> tie, rounds up)
1842 assert_eq!(
1843 f16::from_f64(min_sub_f * 1.49).to_bits(),
1844 min_sub.to_bits() * 1
1845 );
1846 assert_eq!(
1847 f16::from_f64(min_sub_f * 1.50).to_bits(),
1848 min_sub.to_bits() * 2
1849 );
1850 assert_eq!(
1851 f16::from_f64(min_sub_f * 1.51).to_bits(),
1852 min_sub.to_bits() * 2
1853 );
1854
1855 // 0.0000000010_011111 rounded to 0.0000000010 (< tie, no rounding)
1856 // 0.0000000010_100000 rounded to 0.0000000010 (tie and even, remains at even)
1857 // 0.0000000010_100001 rounded to 0.0000000011 (> tie, rounds up)
1858 assert_eq!(
1859 f16::from_f64(min_sub_f * 2.49).to_bits(),
1860 min_sub.to_bits() * 2
1861 );
1862 assert_eq!(
1863 f16::from_f64(min_sub_f * 2.50).to_bits(),
1864 min_sub.to_bits() * 2
1865 );
1866 assert_eq!(
1867 f16::from_f64(min_sub_f * 2.51).to_bits(),
1868 min_sub.to_bits() * 3
1869 );
1870
1871 assert_eq!(
1872 f16::from_f64(2000.49f64).to_bits(),
1873 f16::from_f64(2000.0).to_bits()
1874 );
1875 assert_eq!(
1876 f16::from_f64(2000.50f64).to_bits(),
1877 f16::from_f64(2000.0).to_bits()
1878 );
1879 assert_eq!(
1880 f16::from_f64(2000.51f64).to_bits(),
1881 f16::from_f64(2001.0).to_bits()
1882 );
1883 assert_eq!(
1884 f16::from_f64(2001.49f64).to_bits(),
1885 f16::from_f64(2001.0).to_bits()
1886 );
1887 assert_eq!(
1888 f16::from_f64(2001.50f64).to_bits(),
1889 f16::from_f64(2002.0).to_bits()
1890 );
1891 assert_eq!(
1892 f16::from_f64(2001.51f64).to_bits(),
1893 f16::from_f64(2002.0).to_bits()
1894 );
1895 assert_eq!(
1896 f16::from_f64(2002.49f64).to_bits(),
1897 f16::from_f64(2002.0).to_bits()
1898 );
1899 assert_eq!(
1900 f16::from_f64(2002.50f64).to_bits(),
1901 f16::from_f64(2002.0).to_bits()
1902 );
1903 assert_eq!(
1904 f16::from_f64(2002.51f64).to_bits(),
1905 f16::from_f64(2003.0).to_bits()
1906 );
1907 }
1908
1909 #[test]
1910 fn arithmetic() {
1911 assert_eq!(f16::ONE + f16::ONE, f16::from_f32(2.));
1912 assert_eq!(f16::ONE - f16::ONE, f16::ZERO);
1913 assert_eq!(f16::ONE * f16::ONE, f16::ONE);
1914 assert_eq!(f16::from_f32(2.) * f16::from_f32(2.), f16::from_f32(4.));
1915 assert_eq!(f16::ONE / f16::ONE, f16::ONE);
1916 assert_eq!(f16::from_f32(4.) / f16::from_f32(2.), f16::from_f32(2.));
1917 assert_eq!(f16::from_f32(4.) % f16::from_f32(3.), f16::from_f32(1.));
1918 }
1919
1920 #[cfg(feature = "std")]
1921 #[test]
1922 fn formatting() {
1923 let f = f16::from_f32(0.1152344);
1924
1925 assert_eq!(format!("{:.3}", f), "0.115");
1926 assert_eq!(format!("{:.4}", f), "0.1152");
1927 assert_eq!(format!("{:+.4}", f), "+0.1152");
1928 assert_eq!(format!("{:>+10.4}", f), " +0.1152");
1929
1930 assert_eq!(format!("{:.3?}", f), "0.115");
1931 assert_eq!(format!("{:.4?}", f), "0.1152");
1932 assert_eq!(format!("{:+.4?}", f), "+0.1152");
1933 assert_eq!(format!("{:>+10.4?}", f), " +0.1152");
1934 }
1935
1936 impl quickcheck::Arbitrary for f16 {
1937 fn arbitrary(g: &mut quickcheck::Gen) -> Self {
1938 f16(u16::arbitrary(g))
1939 }
1940 }
1941
1942 #[quickcheck]
1943 fn qc_roundtrip_f16_f32_is_identity(f: f16) -> bool {
1944 let roundtrip = f16::from_f32(f.to_f32());
1945 if f.is_nan() {
1946 roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative()
1947 } else {
1948 f.0 == roundtrip.0
1949 }
1950 }
1951
1952 #[quickcheck]
1953 fn qc_roundtrip_f16_f64_is_identity(f: f16) -> bool {
1954 let roundtrip = f16::from_f64(f.to_f64());
1955 if f.is_nan() {
1956 roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative()
1957 } else {
1958 f.0 == roundtrip.0
1959 }
1960 }
1961 }