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