1 #[cfg(feature = "serde")] 2 use serde::{Deserialize, Serialize}; 3 4 #[cfg(feature = "bytemuck")] 5 use bytemuck::{Pod, Zeroable}; 6 7 use core::{ 8 cmp::Ordering, 9 fmt::{ 10 Binary, Debug, Display, Error, Formatter, LowerExp, LowerHex, Octal, UpperExp, UpperHex, 11 }, 12 num::{FpCategory, ParseFloatError}, 13 str::FromStr, 14 }; 15 16 pub(crate) mod convert; 17 18 /// A 16-bit floating point type implementing the IEEE 754-2008 standard [`binary16`] a.k.a `half` 19 /// format. 20 /// 21 /// This 16-bit floating point type is intended for efficient storage where the full range and 22 /// precision of a larger floating point value is not required. Because [`f16`] is primarily for 23 /// efficient storage, floating point operations such as addition, multiplication, etc. are not 24 /// implemented. Operations should be performed with `f32` or higher-precision types and converted 25 /// to/from [`f16`] as necessary. 26 /// 27 /// [`f16`]: struct.f16.html 28 /// [`binary16`]: https://en.wikipedia.org/wiki/Half-precision_floating-point_format 29 #[allow(non_camel_case_types)] 30 #[derive(Clone, Copy, Default)] 31 #[repr(transparent)] 32 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 33 #[cfg_attr(feature = "bytemuck", derive(Zeroable, Pod))] 34 pub struct f16(u16); 35 36 #[cfg(feature = "num-traits")] 37 mod impl_num_traits { 38 use super::f16; 39 use num_traits::{FromPrimitive, ToPrimitive}; 40 41 impl ToPrimitive for f16 { to_i64(&self) -> Option<i64>42 fn to_i64(&self) -> Option<i64> { 43 Self::to_f32(*self).to_i64() 44 } to_u64(&self) -> Option<u64>45 fn to_u64(&self) -> Option<u64> { 46 Self::to_f32(*self).to_u64() 47 } to_i8(&self) -> Option<i8>48 fn to_i8(&self) -> Option<i8> { 49 Self::to_f32(*self).to_i8() 50 } to_u8(&self) -> Option<u8>51 fn to_u8(&self) -> Option<u8> { 52 Self::to_f32(*self).to_u8() 53 } to_i16(&self) -> Option<i16>54 fn to_i16(&self) -> Option<i16> { 55 Self::to_f32(*self).to_i16() 56 } to_u16(&self) -> Option<u16>57 fn to_u16(&self) -> Option<u16> { 58 Self::to_f32(*self).to_u16() 59 } to_i32(&self) -> Option<i32>60 fn to_i32(&self) -> Option<i32> { 61 Self::to_f32(*self).to_i32() 62 } to_u32(&self) -> Option<u32>63 fn to_u32(&self) -> Option<u32> { 64 Self::to_f32(*self).to_u32() 65 } to_f32(&self) -> Option<f32>66 fn to_f32(&self) -> Option<f32> { 67 Some(Self::to_f32(*self)) 68 } to_f64(&self) -> Option<f64>69 fn to_f64(&self) -> Option<f64> { 70 Some(Self::to_f64(*self)) 71 } 72 } 73 74 impl FromPrimitive for f16 { from_i64(n: i64) -> Option<Self>75 fn from_i64(n: i64) -> Option<Self> { 76 n.to_f32().map(|x| Self::from_f32(x)) 77 } from_u64(n: u64) -> Option<Self>78 fn from_u64(n: u64) -> Option<Self> { 79 n.to_f32().map(|x| Self::from_f32(x)) 80 } from_i8(n: i8) -> Option<Self>81 fn from_i8(n: i8) -> Option<Self> { 82 n.to_f32().map(|x| Self::from_f32(x)) 83 } from_u8(n: u8) -> Option<Self>84 fn from_u8(n: u8) -> Option<Self> { 85 n.to_f32().map(|x| Self::from_f32(x)) 86 } from_i16(n: i16) -> Option<Self>87 fn from_i16(n: i16) -> Option<Self> { 88 n.to_f32().map(|x| Self::from_f32(x)) 89 } from_u16(n: u16) -> Option<Self>90 fn from_u16(n: u16) -> Option<Self> { 91 n.to_f32().map(|x| Self::from_f32(x)) 92 } from_i32(n: i32) -> Option<Self>93 fn from_i32(n: i32) -> Option<Self> { 94 n.to_f32().map(|x| Self::from_f32(x)) 95 } from_u32(n: u32) -> Option<Self>96 fn from_u32(n: u32) -> Option<Self> { 97 n.to_f32().map(|x| Self::from_f32(x)) 98 } from_f32(n: f32) -> Option<Self>99 fn from_f32(n: f32) -> Option<Self> { 100 n.to_f32().map(|x| Self::from_f32(x)) 101 } from_f64(n: f64) -> Option<Self>102 fn from_f64(n: f64) -> Option<Self> { 103 n.to_f64().map(|x| Self::from_f64(x)) 104 } 105 } 106 } 107 108 #[deprecated( 109 since = "1.4.0", 110 note = "all constants moved to associated constants of [`f16`](../struct.f16.html)" 111 )] 112 pub mod consts { 113 //! Useful `f16` constants. 114 115 use super::f16; 116 117 /// Approximate number of [`f16`](../struct.f16.html) significant digits in base 10. 118 #[deprecated( 119 since = "1.4.0", 120 note = "moved to [`f16::DIGITS`](../struct.f16.html#associatedconstant.DIGITS)" 121 )] 122 pub const DIGITS: u32 = f16::DIGITS; 123 /// [`f16`](../struct.f16.html) 124 /// [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value. 125 /// 126 /// This is the difference between 1.0 and the next largest representable number. 127 #[deprecated( 128 since = "1.4.0", 129 note = "moved to [`f16::EPSILON`](../struct.f16.html#associatedconstant.EPSILON)" 130 )] 131 pub const EPSILON: f16 = f16::EPSILON; 132 /// [`f16`](../struct.f16.html) positive Infinity (+∞). 133 #[deprecated( 134 since = "1.4.0", 135 note = "moved to [`f16::INFINITY`](../struct.f16.html#associatedconstant.INFINITY)" 136 )] 137 pub const INFINITY: f16 = f16::INFINITY; 138 /// Number of [`f16`](../struct.f16.html) significant digits in base 2. 139 #[deprecated( 140 since = "1.4.0", 141 note = "moved to [`f16::MANTISSA_DIGITS`](../struct.f16.html#associatedconstant.MANTISSA_DIGITS)" 142 )] 143 pub const MANTISSA_DIGITS: u32 = f16::MANTISSA_DIGITS; 144 /// Largest finite [`f16`](../struct.f16.html) value. 145 #[deprecated( 146 since = "1.4.0", 147 note = "moved to [`f16::MAX`](../struct.f16.html#associatedconstant.MAX)" 148 )] 149 pub const MAX: f16 = f16::MAX; 150 /// Maximum possible [`f16`](../struct.f16.html) power of 10 exponent. 151 #[deprecated( 152 since = "1.4.0", 153 note = "moved to [`f16::MAX_10_EXP`](../struct.f16.html#associatedconstant.MAX_10_EXP)" 154 )] 155 pub const MAX_10_EXP: i32 = f16::MAX_10_EXP; 156 /// Maximum possible [`f16`](../struct.f16.html) power of 2 exponent. 157 #[deprecated( 158 since = "1.4.0", 159 note = "moved to [`f16::MAX_EXP`](../struct.f16.html#associatedconstant.MAX_EXP)" 160 )] 161 pub const MAX_EXP: i32 = f16::MAX_EXP; 162 /// Smallest finite [`f16`](../struct.f16.html) value. 163 #[deprecated( 164 since = "1.4.0", 165 note = "moved to [`f16::MIN`](../struct.f16.html#associatedconstant.MIN)" 166 )] 167 pub const MIN: f16 = f16::MIN; 168 /// Minimum possible normal [`f16`](../struct.f16.html) power of 10 exponent. 169 #[deprecated( 170 since = "1.4.0", 171 note = "moved to [`f16::MIN_10_EXP`](../struct.f16.html#associatedconstant.MIN_10_EXP)" 172 )] 173 pub const MIN_10_EXP: i32 = f16::MIN_10_EXP; 174 /// One greater than the minimum possible normal [`f16`](../struct.f16.html) power of 2 exponent. 175 #[deprecated( 176 since = "1.4.0", 177 note = "moved to [`f16::MIN_EXP`](../struct.f16.html#associatedconstant.MIN_EXP)" 178 )] 179 pub const MIN_EXP: i32 = f16::MIN_EXP; 180 /// Smallest positive normal [`f16`](../struct.f16.html) value. 181 #[deprecated( 182 since = "1.4.0", 183 note = "moved to [`f16::MIN_POSITIVE`](../struct.f16.html#associatedconstant.MIN_POSITIVE)" 184 )] 185 pub const MIN_POSITIVE: f16 = f16::MIN_POSITIVE; 186 /// [`f16`](../struct.f16.html) Not a Number (NaN). 187 #[deprecated( 188 since = "1.4.0", 189 note = "moved to [`f16::NAN`](../struct.f16.html#associatedconstant.NAN)" 190 )] 191 pub const NAN: f16 = f16::NAN; 192 /// [`f16`](../struct.f16.html) negative infinity (-∞). 193 #[deprecated( 194 since = "1.4.0", 195 note = "moved to [`f16::NEG_INFINITY`](../struct.f16.html#associatedconstant.NEG_INFINITY)" 196 )] 197 pub const NEG_INFINITY: f16 = f16::NEG_INFINITY; 198 /// The radix or base of the internal representation of [`f16`](../struct.f16.html). 199 #[deprecated( 200 since = "1.4.0", 201 note = "moved to [`f16::RADIX`](../struct.f16.html#associatedconstant.RADIX)" 202 )] 203 pub const RADIX: u32 = f16::RADIX; 204 205 /// Minimum positive subnormal [`f16`](../struct.f16.html) value. 206 #[deprecated( 207 since = "1.4.0", 208 note = "moved to [`f16::MIN_POSITIVE_SUBNORMAL`](../struct.f16.html#associatedconstant.MIN_POSITIVE_SUBNORMAL)" 209 )] 210 pub const MIN_POSITIVE_SUBNORMAL: f16 = f16::MIN_POSITIVE_SUBNORMAL; 211 /// Maximum subnormal [`f16`](../struct.f16.html) value. 212 #[deprecated( 213 since = "1.4.0", 214 note = "moved to [`f16::MAX_SUBNORMAL`](../struct.f16.html#associatedconstant.MAX_SUBNORMAL)" 215 )] 216 pub const MAX_SUBNORMAL: f16 = f16::MAX_SUBNORMAL; 217 218 /// [`f16`](../struct.f16.html) 1 219 #[deprecated( 220 since = "1.4.0", 221 note = "moved to [`f16::ONE`](../struct.f16.html#associatedconstant.ONE)" 222 )] 223 pub const ONE: f16 = f16::ONE; 224 /// [`f16`](../struct.f16.html) 0 225 #[deprecated( 226 since = "1.4.0", 227 note = "moved to [`f16::ZERO`](../struct.f16.html#associatedconstant.ZERO)" 228 )] 229 pub const ZERO: f16 = f16::ZERO; 230 /// [`f16`](../struct.f16.html) -0 231 #[deprecated( 232 since = "1.4.0", 233 note = "moved to [`f16::NEG_ZERO`](../struct.f16.html#associatedconstant.NEG_ZERO)" 234 )] 235 pub const NEG_ZERO: f16 = f16::NEG_ZERO; 236 237 /// [`f16`](../struct.f16.html) Euler's number (ℯ). 238 #[deprecated( 239 since = "1.4.0", 240 note = "moved to [`f16::E`](../struct.f16.html#associatedconstant.E)" 241 )] 242 pub const E: f16 = f16::E; 243 /// [`f16`](../struct.f16.html) Archimedes' constant (π). 244 #[deprecated( 245 since = "1.4.0", 246 note = "moved to [`f16::PI`](../struct.f16.html#associatedconstant.PI)" 247 )] 248 pub const PI: f16 = f16::PI; 249 /// [`f16`](../struct.f16.html) 1/π 250 #[deprecated( 251 since = "1.4.0", 252 note = "moved to [`f16::FRAC_1_PI`](../struct.f16.html#associatedconstant.FRAC_1_PI)" 253 )] 254 pub const FRAC_1_PI: f16 = f16::FRAC_1_PI; 255 /// [`f16`](../struct.f16.html) 1/√2 256 #[deprecated( 257 since = "1.4.0", 258 note = "moved to [`f16::FRAC_1_SQRT_2`](../struct.f16.html#associatedconstant.FRAC_1_SQRT_2)" 259 )] 260 pub const FRAC_1_SQRT_2: f16 = f16::FRAC_1_SQRT_2; 261 /// [`f16`](../struct.f16.html) 2/π 262 #[deprecated( 263 since = "1.4.0", 264 note = "moved to [`f16::FRAC_2_PI`](../struct.f16.html#associatedconstant.FRAC_2_PI)" 265 )] 266 pub const FRAC_2_PI: f16 = f16::FRAC_2_PI; 267 /// [`f16`](../struct.f16.html) 2/√π 268 #[deprecated( 269 since = "1.4.0", 270 note = "moved to [`f16::FRAC_2_SQRT_PI`](../struct.f16.html#associatedconstant.FRAC_2_SQRT_PI)" 271 )] 272 pub const FRAC_2_SQRT_PI: f16 = f16::FRAC_2_SQRT_PI; 273 /// [`f16`](../struct.f16.html) π/2 274 #[deprecated( 275 since = "1.4.0", 276 note = "moved to [`f16::FRAC_PI_2`](../struct.f16.html#associatedconstant.FRAC_PI_2)" 277 )] 278 pub const FRAC_PI_2: f16 = f16::FRAC_PI_2; 279 /// [`f16`](../struct.f16.html) π/3 280 #[deprecated( 281 since = "1.4.0", 282 note = "moved to [`f16::FRAC_PI_3`](../struct.f16.html#associatedconstant.FRAC_PI_3)" 283 )] 284 pub const FRAC_PI_3: f16 = f16::FRAC_PI_3; 285 /// [`f16`](../struct.f16.html) π/4 286 #[deprecated( 287 since = "1.4.0", 288 note = "moved to [`f16::FRAC_PI_4`](../struct.f16.html#associatedconstant.FRAC_PI_4)" 289 )] 290 pub const FRAC_PI_4: f16 = f16::FRAC_PI_4; 291 /// [`f16`](../struct.f16.html) π/6 292 #[deprecated( 293 since = "1.4.0", 294 note = "moved to [`f16::FRAC_PI_6`](../struct.f16.html#associatedconstant.FRAC_PI_6)" 295 )] 296 pub const FRAC_PI_6: f16 = f16::FRAC_PI_6; 297 /// [`f16`](../struct.f16.html) π/8 298 #[deprecated( 299 since = "1.4.0", 300 note = "moved to [`f16::FRAC_PI_8`](../struct.f16.html#associatedconstant.FRAC_PI_8)" 301 )] 302 pub const FRAC_PI_8: f16 = f16::FRAC_PI_8; 303 /// [`f16`](../struct.f16.html) 10 304 #[deprecated( 305 since = "1.4.0", 306 note = "moved to [`f16::LN_10`](../struct.f16.html#associatedconstant.LN_10)" 307 )] 308 pub const LN_10: f16 = f16::LN_10; 309 /// [`f16`](../struct.f16.html) 2 310 #[deprecated( 311 since = "1.4.0", 312 note = "moved to [`f16::LN_2`](../struct.f16.html#associatedconstant.LN_2)" 313 )] 314 pub const LN_2: f16 = f16::LN_2; 315 /// [`f16`](../struct.f16.html) ₁₀ℯ 316 #[deprecated( 317 since = "1.4.0", 318 note = "moved to [`f16::LOG10_E`](../struct.f16.html#associatedconstant.LOG10_E)" 319 )] 320 pub const LOG10_E: f16 = f16::LOG10_E; 321 /// [`f16`](../struct.f16.html) ₂ℯ 322 #[deprecated( 323 since = "1.4.0", 324 note = "moved to [`f16::LOG2_E`](../struct.f16.html#associatedconstant.LOG2_E)" 325 )] 326 pub const LOG2_E: f16 = f16::LOG2_E; 327 /// [`f16`](../struct.f16.html) √2 328 #[deprecated( 329 since = "1.4.0", 330 note = "moved to [`f16::SQRT_2`](../struct.f16.html#associatedconstant.SQRT_2)" 331 )] 332 pub const SQRT_2: f16 = f16::SQRT_2; 333 } 334 335 impl f16 { 336 /// Constructs a 16-bit floating point value from the raw bits. 337 #[inline] from_bits(bits: u16) -> f16338 pub const fn from_bits(bits: u16) -> f16 { 339 f16(bits) 340 } 341 342 /// Constructs a 16-bit floating point value from a 32-bit floating point value. 343 /// 344 /// If the 32-bit value is to large to fit in 16-bits, ±∞ will result. NaN values are 345 /// preserved. 32-bit subnormal values are too tiny to be represented in 16-bits and result in 346 /// ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit subnormals 347 /// or ±0. All other values are truncated and rounded to the nearest representable 16-bit 348 /// value. 349 #[inline] from_f32(value: f32) -> f16350 pub fn from_f32(value: f32) -> f16 { 351 f16(convert::f32_to_f16(value)) 352 } 353 354 /// Constructs a 16-bit floating point value from a 64-bit floating point value. 355 /// 356 /// If the 64-bit value is to large to fit in 16-bits, ±∞ will result. NaN values are 357 /// preserved. 64-bit subnormal values are too tiny to be represented in 16-bits and result in 358 /// ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit subnormals 359 /// or ±0. All other values are truncated and rounded to the nearest representable 16-bit 360 /// value. 361 #[inline] from_f64(value: f64) -> f16362 pub fn from_f64(value: f64) -> f16 { 363 f16(convert::f64_to_f16(value)) 364 } 365 366 /// Converts a [`f16`](struct.f16.html) into the underlying bit representation. 367 #[inline] to_bits(self) -> u16368 pub const fn to_bits(self) -> u16 { 369 self.0 370 } 371 372 /// Return the memory representation of the underlying bit representation as a byte array in 373 /// little-endian byte order. 374 /// 375 /// # Examples 376 /// 377 /// ```rust 378 /// # use half::prelude::*; 379 /// let bytes = f16::from_f32(12.5).to_le_bytes(); 380 /// assert_eq!(bytes, [0x40, 0x4A]); 381 /// ``` 382 #[inline] to_le_bytes(self) -> [u8; 2]383 pub fn to_le_bytes(self) -> [u8; 2] { 384 self.0.to_le_bytes() 385 } 386 387 /// Return the memory representation of the underlying bit representation as a byte array in 388 /// big-endian (network) byte order. 389 /// 390 /// # Examples 391 /// 392 /// ```rust 393 /// # use half::prelude::*; 394 /// let bytes = f16::from_f32(12.5).to_be_bytes(); 395 /// assert_eq!(bytes, [0x4A, 0x40]); 396 /// ``` 397 #[inline] to_be_bytes(self) -> [u8; 2]398 pub fn to_be_bytes(self) -> [u8; 2] { 399 self.0.to_be_bytes() 400 } 401 402 /// Return the memory representation of the underlying bit representation as a byte array in 403 /// native byte order. 404 /// 405 /// As the target platform's native endianness is used, portable code should use `to_be_bytes` 406 /// or `to_le_bytes`, as appropriate, instead. 407 /// 408 /// # Examples 409 /// 410 /// ```rust 411 /// # use half::prelude::*; 412 /// let bytes = f16::from_f32(12.5).to_ne_bytes(); 413 /// assert_eq!(bytes, if cfg!(target_endian = "big") { 414 /// [0x4A, 0x40] 415 /// } else { 416 /// [0x40, 0x4A] 417 /// }); 418 /// ``` 419 #[inline] to_ne_bytes(self) -> [u8; 2]420 pub fn to_ne_bytes(self) -> [u8; 2] { 421 self.0.to_ne_bytes() 422 } 423 424 /// Create a floating point value from its representation as a byte array in little endian. 425 /// 426 /// # Examples 427 /// 428 /// ```rust 429 /// # use half::prelude::*; 430 /// let value = f16::from_le_bytes([0x40, 0x4A]); 431 /// assert_eq!(value, f16::from_f32(12.5)); 432 /// ``` 433 #[inline] from_le_bytes(bytes: [u8; 2]) -> f16434 pub fn from_le_bytes(bytes: [u8; 2]) -> f16 { 435 f16::from_bits(u16::from_le_bytes(bytes)) 436 } 437 438 /// Create a floating point value from its representation as a byte array in big endian. 439 /// 440 /// # Examples 441 /// 442 /// ```rust 443 /// # use half::prelude::*; 444 /// let value = f16::from_be_bytes([0x4A, 0x40]); 445 /// assert_eq!(value, f16::from_f32(12.5)); 446 /// ``` 447 #[inline] from_be_bytes(bytes: [u8; 2]) -> f16448 pub fn from_be_bytes(bytes: [u8; 2]) -> f16 { 449 f16::from_bits(u16::from_be_bytes(bytes)) 450 } 451 452 /// Create a floating point value from its representation as a byte array in native endian. 453 /// 454 /// As the target platform's native endianness is used, portable code likely wants to use 455 /// `from_be_bytes` or `from_le_bytes`, as appropriate instead. 456 /// 457 /// # Examples 458 /// 459 /// ```rust 460 /// # use half::prelude::*; 461 /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") { 462 /// [0x4A, 0x40] 463 /// } else { 464 /// [0x40, 0x4A] 465 /// }); 466 /// assert_eq!(value, f16::from_f32(12.5)); 467 /// ``` 468 #[inline] from_ne_bytes(bytes: [u8; 2]) -> f16469 pub fn from_ne_bytes(bytes: [u8; 2]) -> f16 { 470 f16::from_bits(u16::from_ne_bytes(bytes)) 471 } 472 473 /// Converts a [`f16`](struct.f16.html) into the underlying bit representation. 474 #[deprecated(since = "1.2.0", note = "renamed to [`to_bits`](#method.to_bits)")] 475 #[inline] as_bits(self) -> u16476 pub fn as_bits(self) -> u16 { 477 self.to_bits() 478 } 479 480 /// Converts a [`f16`](struct.f16.html) value into a `f32` value. 481 /// 482 /// This conversion is lossless as all 16-bit floating point values can be represented exactly 483 /// in 32-bit floating point. 484 #[inline] to_f32(self) -> f32485 pub fn to_f32(self) -> f32 { 486 convert::f16_to_f32(self.0) 487 } 488 489 /// Converts a [`f16`](struct.f16.html) value into a `f64` value. 490 /// 491 /// This conversion is lossless as all 16-bit floating point values can be represented exactly 492 /// in 64-bit floating point. 493 #[inline] to_f64(self) -> f64494 pub fn to_f64(self) -> f64 { 495 convert::f16_to_f64(self.0) 496 } 497 498 /// Returns `true` if this value is `NaN` and `false` otherwise. 499 /// 500 /// # Examples 501 /// 502 /// ```rust 503 /// # use half::prelude::*; 504 /// 505 /// let nan = f16::NAN; 506 /// let f = f16::from_f32(7.0_f32); 507 /// 508 /// assert!(nan.is_nan()); 509 /// assert!(!f.is_nan()); 510 /// ``` 511 #[inline] is_nan(self) -> bool512 pub const fn is_nan(self) -> bool { 513 self.0 & 0x7FFFu16 > 0x7C00u16 514 } 515 516 /// Returns `true` if this value is ±∞ and `false` 517 /// otherwise. 518 /// 519 /// # Examples 520 /// 521 /// ```rust 522 /// # use half::prelude::*; 523 /// 524 /// let f = f16::from_f32(7.0f32); 525 /// let inf = f16::INFINITY; 526 /// let neg_inf = f16::NEG_INFINITY; 527 /// let nan = f16::NAN; 528 /// 529 /// assert!(!f.is_infinite()); 530 /// assert!(!nan.is_infinite()); 531 /// 532 /// assert!(inf.is_infinite()); 533 /// assert!(neg_inf.is_infinite()); 534 /// ``` 535 #[inline] is_infinite(self) -> bool536 pub const fn is_infinite(self) -> bool { 537 self.0 & 0x7FFFu16 == 0x7C00u16 538 } 539 540 /// Returns `true` if this number is neither infinite nor `NaN`. 541 /// 542 /// # Examples 543 /// 544 /// ```rust 545 /// # use half::prelude::*; 546 /// 547 /// let f = f16::from_f32(7.0f32); 548 /// let inf = f16::INFINITY; 549 /// let neg_inf = f16::NEG_INFINITY; 550 /// let nan = f16::NAN; 551 /// 552 /// assert!(f.is_finite()); 553 /// 554 /// assert!(!nan.is_finite()); 555 /// assert!(!inf.is_finite()); 556 /// assert!(!neg_inf.is_finite()); 557 /// ``` 558 #[inline] is_finite(self) -> bool559 pub const fn is_finite(self) -> bool { 560 self.0 & 0x7C00u16 != 0x7C00u16 561 } 562 563 /// Returns `true` if the number is neither zero, infinite, subnormal, or `NaN`. 564 /// 565 /// # Examples 566 /// 567 /// ```rust 568 /// # use half::prelude::*; 569 /// 570 /// let min = f16::MIN_POSITIVE; 571 /// let max = f16::MAX; 572 /// let lower_than_min = f16::from_f32(1.0e-10_f32); 573 /// let zero = f16::from_f32(0.0_f32); 574 /// 575 /// assert!(min.is_normal()); 576 /// assert!(max.is_normal()); 577 /// 578 /// assert!(!zero.is_normal()); 579 /// assert!(!f16::NAN.is_normal()); 580 /// assert!(!f16::INFINITY.is_normal()); 581 /// // Values between `0` and `min` are Subnormal. 582 /// assert!(!lower_than_min.is_normal()); 583 /// ``` 584 #[inline] is_normal(self) -> bool585 pub fn is_normal(self) -> bool { 586 let exp = self.0 & 0x7C00u16; 587 exp != 0x7C00u16 && exp != 0 588 } 589 590 /// Returns the floating point category of the number. 591 /// 592 /// If only one property is going to be tested, it is generally faster to use the specific 593 /// predicate instead. 594 /// 595 /// # Examples 596 /// 597 /// ```rust 598 /// use std::num::FpCategory; 599 /// # use half::prelude::*; 600 /// 601 /// let num = f16::from_f32(12.4_f32); 602 /// let inf = f16::INFINITY; 603 /// 604 /// assert_eq!(num.classify(), FpCategory::Normal); 605 /// assert_eq!(inf.classify(), FpCategory::Infinite); 606 /// ``` classify(self) -> FpCategory607 pub fn classify(self) -> FpCategory { 608 let exp = self.0 & 0x7C00u16; 609 let man = self.0 & 0x03FFu16; 610 match (exp, man) { 611 (0, 0) => FpCategory::Zero, 612 (0, _) => FpCategory::Subnormal, 613 (0x7C00u16, 0) => FpCategory::Infinite, 614 (0x7C00u16, _) => FpCategory::Nan, 615 _ => FpCategory::Normal, 616 } 617 } 618 619 /// Returns a number that represents the sign of `self`. 620 /// 621 /// * `1.0` if the number is positive, `+0.0` or `INFINITY` 622 /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` 623 /// * `NAN` if the number is `NAN` 624 /// 625 /// # Examples 626 /// 627 /// ```rust 628 /// # use half::prelude::*; 629 /// 630 /// let f = f16::from_f32(3.5_f32); 631 /// 632 /// assert_eq!(f.signum(), f16::from_f32(1.0)); 633 /// assert_eq!(f16::NEG_INFINITY.signum(), f16::from_f32(-1.0)); 634 /// 635 /// assert!(f16::NAN.signum().is_nan()); 636 /// ``` signum(self) -> f16637 pub fn signum(self) -> f16 { 638 if self.is_nan() { 639 self 640 } else if self.0 & 0x8000u16 != 0 { 641 f16::from_f32(-1.0) 642 } else { 643 f16::from_f32(1.0) 644 } 645 } 646 647 /// Returns `true` if and only if `self` has a positive sign, including `+0.0`, `NaNs` with a 648 /// positive sign bit and +∞. 649 /// 650 /// # Examples 651 /// 652 /// ```rust 653 /// # use half::prelude::*; 654 /// 655 /// let nan = f16::NAN; 656 /// let f = f16::from_f32(7.0_f32); 657 /// let g = f16::from_f32(-7.0_f32); 658 /// 659 /// assert!(f.is_sign_positive()); 660 /// assert!(!g.is_sign_positive()); 661 /// // `NaN` can be either positive or negative 662 /// assert!(nan.is_sign_positive() != nan.is_sign_negative()); 663 /// ``` 664 #[inline] is_sign_positive(self) -> bool665 pub const fn is_sign_positive(self) -> bool { 666 self.0 & 0x8000u16 == 0 667 } 668 669 /// Returns `true` if and only if `self` has a negative sign, including `-0.0`, `NaNs` with a 670 /// negative sign bit and −∞. 671 /// 672 /// # Examples 673 /// 674 /// ```rust 675 /// # use half::prelude::*; 676 /// 677 /// let nan = f16::NAN; 678 /// let f = f16::from_f32(7.0f32); 679 /// let g = f16::from_f32(-7.0f32); 680 /// 681 /// assert!(!f.is_sign_negative()); 682 /// assert!(g.is_sign_negative()); 683 /// // `NaN` can be either positive or negative 684 /// assert!(nan.is_sign_positive() != nan.is_sign_negative()); 685 /// ``` 686 #[inline] is_sign_negative(self) -> bool687 pub const fn is_sign_negative(self) -> bool { 688 self.0 & 0x8000u16 != 0 689 } 690 691 /// Approximate number of [`f16`](struct.f16.html) significant digits in base 10. 692 pub const DIGITS: u32 = 3; 693 /// [`f16`](struct.f16.html) 694 /// [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value. 695 /// 696 /// This is the difference between 1.0 and the next largest representable number. 697 pub const EPSILON: f16 = f16(0x1400u16); 698 /// [`f16`](struct.f16.html) positive Infinity (+∞). 699 pub const INFINITY: f16 = f16(0x7C00u16); 700 /// Number of [`f16`](struct.f16.html) significant digits in base 2. 701 pub const MANTISSA_DIGITS: u32 = 11; 702 /// Largest finite [`f16`](struct.f16.html) value. 703 pub const MAX: f16 = f16(0x7BFF); 704 /// Maximum possible [`f16`](struct.f16.html) power of 10 exponent. 705 pub const MAX_10_EXP: i32 = 4; 706 /// Maximum possible [`f16`](struct.f16.html) power of 2 exponent. 707 pub const MAX_EXP: i32 = 16; 708 /// Smallest finite [`f16`](struct.f16.html) value. 709 pub const MIN: f16 = f16(0xFBFF); 710 /// Minimum possible normal [`f16`](struct.f16.html) power of 10 exponent. 711 pub const MIN_10_EXP: i32 = -4; 712 /// One greater than the minimum possible normal [`f16`](struct.f16.html) power of 2 exponent. 713 pub const MIN_EXP: i32 = -13; 714 /// Smallest positive normal [`f16`](struct.f16.html) value. 715 pub const MIN_POSITIVE: f16 = f16(0x0400u16); 716 /// [`f16`](struct.f16.html) Not a Number (NaN). 717 pub const NAN: f16 = f16(0x7E00u16); 718 /// [`f16`](struct.f16.html) negative infinity (-∞). 719 pub const NEG_INFINITY: f16 = f16(0xFC00u16); 720 /// The radix or base of the internal representation of [`f16`](struct.f16.html). 721 pub const RADIX: u32 = 2; 722 723 /// Minimum positive subnormal [`f16`](struct.f16.html) value. 724 pub const MIN_POSITIVE_SUBNORMAL: f16 = f16(0x0001u16); 725 /// Maximum subnormal [`f16`](struct.f16.html) value. 726 pub const MAX_SUBNORMAL: f16 = f16(0x03FFu16); 727 728 /// [`f16`](struct.f16.html) 1 729 pub const ONE: f16 = f16(0x3C00u16); 730 /// [`f16`](struct.f16.html) 0 731 pub const ZERO: f16 = f16(0x0000u16); 732 /// [`f16`](struct.f16.html) -0 733 pub const NEG_ZERO: f16 = f16(0x8000u16); 734 735 /// [`f16`](struct.f16.html) Euler's number (ℯ). 736 pub const E: f16 = f16(0x4170u16); 737 /// [`f16`](struct.f16.html) Archimedes' constant (π). 738 pub const PI: f16 = f16(0x4248u16); 739 /// [`f16`](struct.f16.html) 1/π 740 pub const FRAC_1_PI: f16 = f16(0x3518u16); 741 /// [`f16`](struct.f16.html) 1/√2 742 pub const FRAC_1_SQRT_2: f16 = f16(0x39A8u16); 743 /// [`f16`](struct.f16.html) 2/π 744 pub const FRAC_2_PI: f16 = f16(0x3918u16); 745 /// [`f16`](struct.f16.html) 2/√π 746 pub const FRAC_2_SQRT_PI: f16 = f16(0x3C83u16); 747 /// [`f16`](struct.f16.html) π/2 748 pub const FRAC_PI_2: f16 = f16(0x3E48u16); 749 /// [`f16`](struct.f16.html) π/3 750 pub const FRAC_PI_3: f16 = f16(0x3C30u16); 751 /// [`f16`](struct.f16.html) π/4 752 pub const FRAC_PI_4: f16 = f16(0x3A48u16); 753 /// [`f16`](struct.f16.html) π/6 754 pub const FRAC_PI_6: f16 = f16(0x3830u16); 755 /// [`f16`](struct.f16.html) π/8 756 pub const FRAC_PI_8: f16 = f16(0x3648u16); 757 /// [`f16`](struct.f16.html) 10 758 pub const LN_10: f16 = f16(0x409Bu16); 759 /// [`f16`](struct.f16.html) 2 760 pub const LN_2: f16 = f16(0x398Cu16); 761 /// [`f16`](struct.f16.html) ₁₀ℯ 762 pub const LOG10_E: f16 = f16(0x36F3u16); 763 /// [`f16`](struct.f16.html) ₁₀2 764 pub const LOG10_2: f16 = f16(0x34D1u16); 765 /// [`f16`](struct.f16.html) ₂ℯ 766 pub const LOG2_E: f16 = f16(0x3DC5u16); 767 /// [`f16`](struct.f16.html) ₂10 768 pub const LOG2_10: f16 = f16(0x42A5u16); 769 /// [`f16`](struct.f16.html) √2 770 pub const SQRT_2: f16 = f16(0x3DA8u16); 771 } 772 773 impl From<f16> for f32 { 774 #[inline] from(x: f16) -> f32775 fn from(x: f16) -> f32 { 776 x.to_f32() 777 } 778 } 779 780 impl From<f16> for f64 { 781 #[inline] from(x: f16) -> f64782 fn from(x: f16) -> f64 { 783 x.to_f64() 784 } 785 } 786 787 impl From<i8> for f16 { 788 #[inline] from(x: i8) -> f16789 fn from(x: i8) -> f16 { 790 // Convert to f32, then to f16 791 f16::from_f32(f32::from(x)) 792 } 793 } 794 795 impl From<u8> for f16 { 796 #[inline] from(x: u8) -> f16797 fn from(x: u8) -> f16 { 798 // Convert to f32, then to f16 799 f16::from_f32(f32::from(x)) 800 } 801 } 802 803 impl PartialEq for f16 { eq(&self, other: &f16) -> bool804 fn eq(&self, other: &f16) -> bool { 805 if self.is_nan() || other.is_nan() { 806 false 807 } else { 808 (self.0 == other.0) || ((self.0 | other.0) & 0x7FFFu16 == 0) 809 } 810 } 811 } 812 813 impl PartialOrd for f16 { partial_cmp(&self, other: &f16) -> Option<Ordering>814 fn partial_cmp(&self, other: &f16) -> Option<Ordering> { 815 if self.is_nan() || other.is_nan() { 816 None 817 } else { 818 let neg = self.0 & 0x8000u16 != 0; 819 let other_neg = other.0 & 0x8000u16 != 0; 820 match (neg, other_neg) { 821 (false, false) => Some(self.0.cmp(&other.0)), 822 (false, true) => { 823 if (self.0 | other.0) & 0x7FFFu16 == 0 { 824 Some(Ordering::Equal) 825 } else { 826 Some(Ordering::Greater) 827 } 828 } 829 (true, false) => { 830 if (self.0 | other.0) & 0x7FFFu16 == 0 { 831 Some(Ordering::Equal) 832 } else { 833 Some(Ordering::Less) 834 } 835 } 836 (true, true) => Some(other.0.cmp(&self.0)), 837 } 838 } 839 } 840 lt(&self, other: &f16) -> bool841 fn lt(&self, other: &f16) -> bool { 842 if self.is_nan() || other.is_nan() { 843 false 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) => self.0 < other.0, 849 (false, true) => false, 850 (true, false) => (self.0 | other.0) & 0x7FFFu16 != 0, 851 (true, true) => self.0 > other.0, 852 } 853 } 854 } 855 le(&self, other: &f16) -> bool856 fn le(&self, other: &f16) -> bool { 857 if self.is_nan() || other.is_nan() { 858 false 859 } else { 860 let neg = self.0 & 0x8000u16 != 0; 861 let other_neg = other.0 & 0x8000u16 != 0; 862 match (neg, other_neg) { 863 (false, false) => self.0 <= other.0, 864 (false, true) => (self.0 | other.0) & 0x7FFFu16 == 0, 865 (true, false) => true, 866 (true, true) => self.0 >= other.0, 867 } 868 } 869 } 870 gt(&self, other: &f16) -> bool871 fn gt(&self, other: &f16) -> bool { 872 if self.is_nan() || other.is_nan() { 873 false 874 } else { 875 let neg = self.0 & 0x8000u16 != 0; 876 let other_neg = other.0 & 0x8000u16 != 0; 877 match (neg, other_neg) { 878 (false, false) => self.0 > other.0, 879 (false, true) => (self.0 | other.0) & 0x7FFFu16 != 0, 880 (true, false) => false, 881 (true, true) => self.0 < other.0, 882 } 883 } 884 } 885 ge(&self, other: &f16) -> bool886 fn ge(&self, other: &f16) -> bool { 887 if self.is_nan() || other.is_nan() { 888 false 889 } else { 890 let neg = self.0 & 0x8000u16 != 0; 891 let other_neg = other.0 & 0x8000u16 != 0; 892 match (neg, other_neg) { 893 (false, false) => self.0 >= other.0, 894 (false, true) => true, 895 (true, false) => (self.0 | other.0) & 0x7FFFu16 == 0, 896 (true, true) => self.0 <= other.0, 897 } 898 } 899 } 900 } 901 902 impl FromStr for f16 { 903 type Err = ParseFloatError; from_str(src: &str) -> Result<f16, ParseFloatError>904 fn from_str(src: &str) -> Result<f16, ParseFloatError> { 905 f32::from_str(src).map(f16::from_f32) 906 } 907 } 908 909 impl Debug for f16 { fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>910 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { 911 write!(f, "{:?}", self.to_f32()) 912 } 913 } 914 915 impl Display for f16 { fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>916 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { 917 write!(f, "{}", self.to_f32()) 918 } 919 } 920 921 impl LowerExp for f16 { fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>922 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { 923 write!(f, "{:e}", self.to_f32()) 924 } 925 } 926 927 impl UpperExp for f16 { fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>928 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { 929 write!(f, "{:E}", self.to_f32()) 930 } 931 } 932 933 impl Binary for f16 { fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>934 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { 935 write!(f, "{:b}", self.0) 936 } 937 } 938 939 impl Octal for f16 { fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>940 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { 941 write!(f, "{:o}", self.0) 942 } 943 } 944 945 impl LowerHex for f16 { fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>946 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { 947 write!(f, "{:x}", self.0) 948 } 949 } 950 951 impl UpperHex for f16 { fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>952 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { 953 write!(f, "{:X}", self.0) 954 } 955 } 956 957 #[allow( 958 clippy::cognitive_complexity, 959 clippy::float_cmp, 960 clippy::neg_cmp_op_on_partial_ord 961 )] 962 #[cfg(test)] 963 mod test { 964 use super::*; 965 use core; 966 use core::cmp::Ordering; 967 use quickcheck_macros::quickcheck; 968 969 #[test] test_f16_consts()970 fn test_f16_consts() { 971 // DIGITS 972 let digits = ((f16::MANTISSA_DIGITS as f32 - 1.0) * 2f32.log10()).floor() as u32; 973 assert_eq!(f16::DIGITS, digits); 974 // sanity check to show test is good 975 let digits32 = ((core::f32::MANTISSA_DIGITS as f32 - 1.0) * 2f32.log10()).floor() as u32; 976 assert_eq!(core::f32::DIGITS, digits32); 977 978 // EPSILON 979 let one = f16::from_f32(1.0); 980 let one_plus_epsilon = f16::from_bits(one.to_bits() + 1); 981 let epsilon = f16::from_f32(one_plus_epsilon.to_f32() - 1.0); 982 assert_eq!(f16::EPSILON, epsilon); 983 // sanity check to show test is good 984 let one_plus_epsilon32 = f32::from_bits(1.0f32.to_bits() + 1); 985 let epsilon32 = one_plus_epsilon32 - 1f32; 986 assert_eq!(core::f32::EPSILON, epsilon32); 987 988 // MAX, MIN and MIN_POSITIVE 989 let max = f16::from_bits(f16::INFINITY.to_bits() - 1); 990 let min = f16::from_bits(f16::NEG_INFINITY.to_bits() - 1); 991 let min_pos = f16::from_f32(2f32.powi(f16::MIN_EXP - 1)); 992 assert_eq!(f16::MAX, max); 993 assert_eq!(f16::MIN, min); 994 assert_eq!(f16::MIN_POSITIVE, min_pos); 995 // sanity check to show test is good 996 let max32 = f32::from_bits(core::f32::INFINITY.to_bits() - 1); 997 let min32 = f32::from_bits(core::f32::NEG_INFINITY.to_bits() - 1); 998 let min_pos32 = 2f32.powi(core::f32::MIN_EXP - 1); 999 assert_eq!(core::f32::MAX, max32); 1000 assert_eq!(core::f32::MIN, min32); 1001 assert_eq!(core::f32::MIN_POSITIVE, min_pos32); 1002 1003 // MIN_10_EXP and MAX_10_EXP 1004 let ten_to_min = 10f32.powi(f16::MIN_10_EXP); 1005 assert!(ten_to_min / 10.0 < f16::MIN_POSITIVE.to_f32()); 1006 assert!(ten_to_min > f16::MIN_POSITIVE.to_f32()); 1007 let ten_to_max = 10f32.powi(f16::MAX_10_EXP); 1008 assert!(ten_to_max < f16::MAX.to_f32()); 1009 assert!(ten_to_max * 10.0 > f16::MAX.to_f32()); 1010 // sanity check to show test is good 1011 let ten_to_min32 = 10f64.powi(core::f32::MIN_10_EXP); 1012 assert!(ten_to_min32 / 10.0 < f64::from(core::f32::MIN_POSITIVE)); 1013 assert!(ten_to_min32 > f64::from(core::f32::MIN_POSITIVE)); 1014 let ten_to_max32 = 10f64.powi(core::f32::MAX_10_EXP); 1015 assert!(ten_to_max32 < f64::from(core::f32::MAX)); 1016 assert!(ten_to_max32 * 10.0 > f64::from(core::f32::MAX)); 1017 } 1018 1019 #[test] test_f16_consts_from_f32()1020 fn test_f16_consts_from_f32() { 1021 let one = f16::from_f32(1.0); 1022 let zero = f16::from_f32(0.0); 1023 let neg_zero = f16::from_f32(-0.0); 1024 let inf = f16::from_f32(core::f32::INFINITY); 1025 let neg_inf = f16::from_f32(core::f32::NEG_INFINITY); 1026 let nan = f16::from_f32(core::f32::NAN); 1027 1028 assert_eq!(f16::ONE, one); 1029 assert_eq!(f16::ZERO, zero); 1030 assert!(zero.is_sign_positive()); 1031 assert_eq!(f16::NEG_ZERO, neg_zero); 1032 assert!(neg_zero.is_sign_negative()); 1033 assert_eq!(f16::INFINITY, inf); 1034 assert_eq!(f16::NEG_INFINITY, neg_inf); 1035 assert!(nan.is_nan()); 1036 assert!(f16::NAN.is_nan()); 1037 1038 let e = f16::from_f32(core::f32::consts::E); 1039 let pi = f16::from_f32(core::f32::consts::PI); 1040 let frac_1_pi = f16::from_f32(core::f32::consts::FRAC_1_PI); 1041 let frac_1_sqrt_2 = f16::from_f32(core::f32::consts::FRAC_1_SQRT_2); 1042 let frac_2_pi = f16::from_f32(core::f32::consts::FRAC_2_PI); 1043 let frac_2_sqrt_pi = f16::from_f32(core::f32::consts::FRAC_2_SQRT_PI); 1044 let frac_pi_2 = f16::from_f32(core::f32::consts::FRAC_PI_2); 1045 let frac_pi_3 = f16::from_f32(core::f32::consts::FRAC_PI_3); 1046 let frac_pi_4 = f16::from_f32(core::f32::consts::FRAC_PI_4); 1047 let frac_pi_6 = f16::from_f32(core::f32::consts::FRAC_PI_6); 1048 let frac_pi_8 = f16::from_f32(core::f32::consts::FRAC_PI_8); 1049 let ln_10 = f16::from_f32(core::f32::consts::LN_10); 1050 let ln_2 = f16::from_f32(core::f32::consts::LN_2); 1051 let log10_e = f16::from_f32(core::f32::consts::LOG10_E); 1052 // core::f32::consts::LOG10_2 requires rustc 1.43.0 1053 let log10_2 = f16::from_f32(2f32.log10()); 1054 let log2_e = f16::from_f32(core::f32::consts::LOG2_E); 1055 // core::f32::consts::LOG2_10 requires rustc 1.43.0 1056 let log2_10 = f16::from_f32(10f32.log2()); 1057 let sqrt_2 = f16::from_f32(core::f32::consts::SQRT_2); 1058 1059 assert_eq!(f16::E, e); 1060 assert_eq!(f16::PI, pi); 1061 assert_eq!(f16::FRAC_1_PI, frac_1_pi); 1062 assert_eq!(f16::FRAC_1_SQRT_2, frac_1_sqrt_2); 1063 assert_eq!(f16::FRAC_2_PI, frac_2_pi); 1064 assert_eq!(f16::FRAC_2_SQRT_PI, frac_2_sqrt_pi); 1065 assert_eq!(f16::FRAC_PI_2, frac_pi_2); 1066 assert_eq!(f16::FRAC_PI_3, frac_pi_3); 1067 assert_eq!(f16::FRAC_PI_4, frac_pi_4); 1068 assert_eq!(f16::FRAC_PI_6, frac_pi_6); 1069 assert_eq!(f16::FRAC_PI_8, frac_pi_8); 1070 assert_eq!(f16::LN_10, ln_10); 1071 assert_eq!(f16::LN_2, ln_2); 1072 assert_eq!(f16::LOG10_E, log10_e); 1073 assert_eq!(f16::LOG10_2, log10_2); 1074 assert_eq!(f16::LOG2_E, log2_e); 1075 assert_eq!(f16::LOG2_10, log2_10); 1076 assert_eq!(f16::SQRT_2, sqrt_2); 1077 } 1078 1079 #[test] test_f16_consts_from_f64()1080 fn test_f16_consts_from_f64() { 1081 let one = f16::from_f64(1.0); 1082 let zero = f16::from_f64(0.0); 1083 let neg_zero = f16::from_f64(-0.0); 1084 let inf = f16::from_f64(core::f64::INFINITY); 1085 let neg_inf = f16::from_f64(core::f64::NEG_INFINITY); 1086 let nan = f16::from_f64(core::f64::NAN); 1087 1088 assert_eq!(f16::ONE, one); 1089 assert_eq!(f16::ZERO, zero); 1090 assert!(zero.is_sign_positive()); 1091 assert_eq!(f16::NEG_ZERO, neg_zero); 1092 assert!(neg_zero.is_sign_negative()); 1093 assert_eq!(f16::INFINITY, inf); 1094 assert_eq!(f16::NEG_INFINITY, neg_inf); 1095 assert!(nan.is_nan()); 1096 assert!(f16::NAN.is_nan()); 1097 1098 let e = f16::from_f64(core::f64::consts::E); 1099 let pi = f16::from_f64(core::f64::consts::PI); 1100 let frac_1_pi = f16::from_f64(core::f64::consts::FRAC_1_PI); 1101 let frac_1_sqrt_2 = f16::from_f64(core::f64::consts::FRAC_1_SQRT_2); 1102 let frac_2_pi = f16::from_f64(core::f64::consts::FRAC_2_PI); 1103 let frac_2_sqrt_pi = f16::from_f64(core::f64::consts::FRAC_2_SQRT_PI); 1104 let frac_pi_2 = f16::from_f64(core::f64::consts::FRAC_PI_2); 1105 let frac_pi_3 = f16::from_f64(core::f64::consts::FRAC_PI_3); 1106 let frac_pi_4 = f16::from_f64(core::f64::consts::FRAC_PI_4); 1107 let frac_pi_6 = f16::from_f64(core::f64::consts::FRAC_PI_6); 1108 let frac_pi_8 = f16::from_f64(core::f64::consts::FRAC_PI_8); 1109 let ln_10 = f16::from_f64(core::f64::consts::LN_10); 1110 let ln_2 = f16::from_f64(core::f64::consts::LN_2); 1111 let log10_e = f16::from_f64(core::f64::consts::LOG10_E); 1112 // core::f64::consts::LOG10_2 requires rustc 1.43.0 1113 let log10_2 = f16::from_f64(2f64.log10()); 1114 let log2_e = f16::from_f64(core::f64::consts::LOG2_E); 1115 // core::f64::consts::LOG2_10 requires rustc 1.43.0 1116 let log2_10 = f16::from_f64(10f64.log2()); 1117 let sqrt_2 = f16::from_f64(core::f64::consts::SQRT_2); 1118 1119 assert_eq!(f16::E, e); 1120 assert_eq!(f16::PI, pi); 1121 assert_eq!(f16::FRAC_1_PI, frac_1_pi); 1122 assert_eq!(f16::FRAC_1_SQRT_2, frac_1_sqrt_2); 1123 assert_eq!(f16::FRAC_2_PI, frac_2_pi); 1124 assert_eq!(f16::FRAC_2_SQRT_PI, frac_2_sqrt_pi); 1125 assert_eq!(f16::FRAC_PI_2, frac_pi_2); 1126 assert_eq!(f16::FRAC_PI_3, frac_pi_3); 1127 assert_eq!(f16::FRAC_PI_4, frac_pi_4); 1128 assert_eq!(f16::FRAC_PI_6, frac_pi_6); 1129 assert_eq!(f16::FRAC_PI_8, frac_pi_8); 1130 assert_eq!(f16::LN_10, ln_10); 1131 assert_eq!(f16::LN_2, ln_2); 1132 assert_eq!(f16::LOG10_E, log10_e); 1133 assert_eq!(f16::LOG10_2, log10_2); 1134 assert_eq!(f16::LOG2_E, log2_e); 1135 assert_eq!(f16::LOG2_10, log2_10); 1136 assert_eq!(f16::SQRT_2, sqrt_2); 1137 } 1138 1139 #[test] test_nan_conversion_to_smaller()1140 fn test_nan_conversion_to_smaller() { 1141 let nan64 = f64::from_bits(0x7FF0_0000_0000_0001u64); 1142 let neg_nan64 = f64::from_bits(0xFFF0_0000_0000_0001u64); 1143 let nan32 = f32::from_bits(0x7F80_0001u32); 1144 let neg_nan32 = f32::from_bits(0xFF80_0001u32); 1145 let nan32_from_64 = nan64 as f32; 1146 let neg_nan32_from_64 = neg_nan64 as f32; 1147 let nan16_from_64 = f16::from_f64(nan64); 1148 let neg_nan16_from_64 = f16::from_f64(neg_nan64); 1149 let nan16_from_32 = f16::from_f32(nan32); 1150 let neg_nan16_from_32 = f16::from_f32(neg_nan32); 1151 1152 assert!(nan64.is_nan() && nan64.is_sign_positive()); 1153 assert!(neg_nan64.is_nan() && neg_nan64.is_sign_negative()); 1154 assert!(nan32.is_nan() && nan32.is_sign_positive()); 1155 assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative()); 1156 assert!(nan32_from_64.is_nan() && nan32_from_64.is_sign_positive()); 1157 assert!(neg_nan32_from_64.is_nan() && neg_nan32_from_64.is_sign_negative()); 1158 assert!(nan16_from_64.is_nan() && nan16_from_64.is_sign_positive()); 1159 assert!(neg_nan16_from_64.is_nan() && neg_nan16_from_64.is_sign_negative()); 1160 assert!(nan16_from_32.is_nan() && nan16_from_32.is_sign_positive()); 1161 assert!(neg_nan16_from_32.is_nan() && neg_nan16_from_32.is_sign_negative()); 1162 } 1163 1164 #[test] test_nan_conversion_to_larger()1165 fn test_nan_conversion_to_larger() { 1166 let nan16 = f16::from_bits(0x7C01u16); 1167 let neg_nan16 = f16::from_bits(0xFC01u16); 1168 let nan32 = f32::from_bits(0x7F80_0001u32); 1169 let neg_nan32 = f32::from_bits(0xFF80_0001u32); 1170 let nan32_from_16 = f32::from(nan16); 1171 let neg_nan32_from_16 = f32::from(neg_nan16); 1172 let nan64_from_16 = f64::from(nan16); 1173 let neg_nan64_from_16 = f64::from(neg_nan16); 1174 let nan64_from_32 = f64::from(nan32); 1175 let neg_nan64_from_32 = f64::from(neg_nan32); 1176 1177 assert!(nan16.is_nan() && nan16.is_sign_positive()); 1178 assert!(neg_nan16.is_nan() && neg_nan16.is_sign_negative()); 1179 assert!(nan32.is_nan() && nan32.is_sign_positive()); 1180 assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative()); 1181 assert!(nan32_from_16.is_nan() && nan32_from_16.is_sign_positive()); 1182 assert!(neg_nan32_from_16.is_nan() && neg_nan32_from_16.is_sign_negative()); 1183 assert!(nan64_from_16.is_nan() && nan64_from_16.is_sign_positive()); 1184 assert!(neg_nan64_from_16.is_nan() && neg_nan64_from_16.is_sign_negative()); 1185 assert!(nan64_from_32.is_nan() && nan64_from_32.is_sign_positive()); 1186 assert!(neg_nan64_from_32.is_nan() && neg_nan64_from_32.is_sign_negative()); 1187 } 1188 1189 #[test] test_f16_to_f32()1190 fn test_f16_to_f32() { 1191 let f = f16::from_f32(7.0); 1192 assert_eq!(f.to_f32(), 7.0f32); 1193 1194 // 7.1 is NOT exactly representable in 16-bit, it's rounded 1195 let f = f16::from_f32(7.1); 1196 let diff = (f.to_f32() - 7.1f32).abs(); 1197 // diff must be <= 4 * EPSILON, as 7 has two more significant bits than 1 1198 assert!(diff <= 4.0 * f16::EPSILON.to_f32()); 1199 1200 assert_eq!(f16::from_bits(0x0000_0001).to_f32(), 2.0f32.powi(-24)); 1201 assert_eq!(f16::from_bits(0x0000_0005).to_f32(), 5.0 * 2.0f32.powi(-24)); 1202 1203 assert_eq!(f16::from_bits(0x0000_0001), f16::from_f32(2.0f32.powi(-24))); 1204 assert_eq!( 1205 f16::from_bits(0x0000_0005), 1206 f16::from_f32(5.0 * 2.0f32.powi(-24)) 1207 ); 1208 } 1209 1210 #[test] test_f16_to_f64()1211 fn test_f16_to_f64() { 1212 let f = f16::from_f64(7.0); 1213 assert_eq!(f.to_f64(), 7.0f64); 1214 1215 // 7.1 is NOT exactly representable in 16-bit, it's rounded 1216 let f = f16::from_f64(7.1); 1217 let diff = (f.to_f64() - 7.1f64).abs(); 1218 // diff must be <= 4 * EPSILON, as 7 has two more significant bits than 1 1219 assert!(diff <= 4.0 * f16::EPSILON.to_f64()); 1220 1221 assert_eq!(f16::from_bits(0x0000_0001).to_f64(), 2.0f64.powi(-24)); 1222 assert_eq!(f16::from_bits(0x0000_0005).to_f64(), 5.0 * 2.0f64.powi(-24)); 1223 1224 assert_eq!(f16::from_bits(0x0000_0001), f16::from_f64(2.0f64.powi(-24))); 1225 assert_eq!( 1226 f16::from_bits(0x0000_0005), 1227 f16::from_f64(5.0 * 2.0f64.powi(-24)) 1228 ); 1229 } 1230 1231 #[test] test_comparisons()1232 fn test_comparisons() { 1233 let zero = f16::from_f64(0.0); 1234 let one = f16::from_f64(1.0); 1235 let neg_zero = f16::from_f64(-0.0); 1236 let neg_one = f16::from_f64(-1.0); 1237 1238 assert_eq!(zero.partial_cmp(&neg_zero), Some(Ordering::Equal)); 1239 assert_eq!(neg_zero.partial_cmp(&zero), Some(Ordering::Equal)); 1240 assert!(zero == neg_zero); 1241 assert!(neg_zero == zero); 1242 assert!(!(zero != neg_zero)); 1243 assert!(!(neg_zero != zero)); 1244 assert!(!(zero < neg_zero)); 1245 assert!(!(neg_zero < zero)); 1246 assert!(zero <= neg_zero); 1247 assert!(neg_zero <= zero); 1248 assert!(!(zero > neg_zero)); 1249 assert!(!(neg_zero > zero)); 1250 assert!(zero >= neg_zero); 1251 assert!(neg_zero >= zero); 1252 1253 assert_eq!(one.partial_cmp(&neg_zero), Some(Ordering::Greater)); 1254 assert_eq!(neg_zero.partial_cmp(&one), Some(Ordering::Less)); 1255 assert!(!(one == neg_zero)); 1256 assert!(!(neg_zero == one)); 1257 assert!(one != neg_zero); 1258 assert!(neg_zero != one); 1259 assert!(!(one < neg_zero)); 1260 assert!(neg_zero < one); 1261 assert!(!(one <= neg_zero)); 1262 assert!(neg_zero <= one); 1263 assert!(one > neg_zero); 1264 assert!(!(neg_zero > one)); 1265 assert!(one >= neg_zero); 1266 assert!(!(neg_zero >= one)); 1267 1268 assert_eq!(one.partial_cmp(&neg_one), Some(Ordering::Greater)); 1269 assert_eq!(neg_one.partial_cmp(&one), Some(Ordering::Less)); 1270 assert!(!(one == neg_one)); 1271 assert!(!(neg_one == one)); 1272 assert!(one != neg_one); 1273 assert!(neg_one != one); 1274 assert!(!(one < neg_one)); 1275 assert!(neg_one < one); 1276 assert!(!(one <= neg_one)); 1277 assert!(neg_one <= one); 1278 assert!(one > neg_one); 1279 assert!(!(neg_one > one)); 1280 assert!(one >= neg_one); 1281 assert!(!(neg_one >= one)); 1282 } 1283 1284 #[test] 1285 #[allow(clippy::erasing_op, clippy::identity_op)] round_to_even_f32()1286 fn round_to_even_f32() { 1287 // smallest positive subnormal = 0b0.0000_0000_01 * 2^-14 = 2^-24 1288 let min_sub = f16::from_bits(1); 1289 let min_sub_f = (-24f32).exp2(); 1290 assert_eq!(f16::from_f32(min_sub_f).to_bits(), min_sub.to_bits()); 1291 assert_eq!(f32::from(min_sub).to_bits(), min_sub_f.to_bits()); 1292 1293 // 0.0000000000_011111 rounded to 0.0000000000 (< tie, no rounding) 1294 // 0.0000000000_100000 rounded to 0.0000000000 (tie and even, remains at even) 1295 // 0.0000000000_100001 rounded to 0.0000000001 (> tie, rounds up) 1296 assert_eq!( 1297 f16::from_f32(min_sub_f * 0.49).to_bits(), 1298 min_sub.to_bits() * 0 1299 ); 1300 assert_eq!( 1301 f16::from_f32(min_sub_f * 0.50).to_bits(), 1302 min_sub.to_bits() * 0 1303 ); 1304 assert_eq!( 1305 f16::from_f32(min_sub_f * 0.51).to_bits(), 1306 min_sub.to_bits() * 1 1307 ); 1308 1309 // 0.0000000001_011111 rounded to 0.0000000001 (< tie, no rounding) 1310 // 0.0000000001_100000 rounded to 0.0000000010 (tie and odd, rounds up to even) 1311 // 0.0000000001_100001 rounded to 0.0000000010 (> tie, rounds up) 1312 assert_eq!( 1313 f16::from_f32(min_sub_f * 1.49).to_bits(), 1314 min_sub.to_bits() * 1 1315 ); 1316 assert_eq!( 1317 f16::from_f32(min_sub_f * 1.50).to_bits(), 1318 min_sub.to_bits() * 2 1319 ); 1320 assert_eq!( 1321 f16::from_f32(min_sub_f * 1.51).to_bits(), 1322 min_sub.to_bits() * 2 1323 ); 1324 1325 // 0.0000000010_011111 rounded to 0.0000000010 (< tie, no rounding) 1326 // 0.0000000010_100000 rounded to 0.0000000010 (tie and even, remains at even) 1327 // 0.0000000010_100001 rounded to 0.0000000011 (> tie, rounds up) 1328 assert_eq!( 1329 f16::from_f32(min_sub_f * 2.49).to_bits(), 1330 min_sub.to_bits() * 2 1331 ); 1332 assert_eq!( 1333 f16::from_f32(min_sub_f * 2.50).to_bits(), 1334 min_sub.to_bits() * 2 1335 ); 1336 assert_eq!( 1337 f16::from_f32(min_sub_f * 2.51).to_bits(), 1338 min_sub.to_bits() * 3 1339 ); 1340 1341 assert_eq!( 1342 f16::from_f32(2000.49f32).to_bits(), 1343 f16::from_f32(2000.0).to_bits() 1344 ); 1345 assert_eq!( 1346 f16::from_f32(2000.50f32).to_bits(), 1347 f16::from_f32(2000.0).to_bits() 1348 ); 1349 assert_eq!( 1350 f16::from_f32(2000.51f32).to_bits(), 1351 f16::from_f32(2001.0).to_bits() 1352 ); 1353 assert_eq!( 1354 f16::from_f32(2001.49f32).to_bits(), 1355 f16::from_f32(2001.0).to_bits() 1356 ); 1357 assert_eq!( 1358 f16::from_f32(2001.50f32).to_bits(), 1359 f16::from_f32(2002.0).to_bits() 1360 ); 1361 assert_eq!( 1362 f16::from_f32(2001.51f32).to_bits(), 1363 f16::from_f32(2002.0).to_bits() 1364 ); 1365 assert_eq!( 1366 f16::from_f32(2002.49f32).to_bits(), 1367 f16::from_f32(2002.0).to_bits() 1368 ); 1369 assert_eq!( 1370 f16::from_f32(2002.50f32).to_bits(), 1371 f16::from_f32(2002.0).to_bits() 1372 ); 1373 assert_eq!( 1374 f16::from_f32(2002.51f32).to_bits(), 1375 f16::from_f32(2003.0).to_bits() 1376 ); 1377 } 1378 1379 #[test] 1380 #[allow(clippy::erasing_op, clippy::identity_op)] round_to_even_f64()1381 fn round_to_even_f64() { 1382 // smallest positive subnormal = 0b0.0000_0000_01 * 2^-14 = 2^-24 1383 let min_sub = f16::from_bits(1); 1384 let min_sub_f = (-24f64).exp2(); 1385 assert_eq!(f16::from_f64(min_sub_f).to_bits(), min_sub.to_bits()); 1386 assert_eq!(f64::from(min_sub).to_bits(), min_sub_f.to_bits()); 1387 1388 // 0.0000000000_011111 rounded to 0.0000000000 (< tie, no rounding) 1389 // 0.0000000000_100000 rounded to 0.0000000000 (tie and even, remains at even) 1390 // 0.0000000000_100001 rounded to 0.0000000001 (> tie, rounds up) 1391 assert_eq!( 1392 f16::from_f64(min_sub_f * 0.49).to_bits(), 1393 min_sub.to_bits() * 0 1394 ); 1395 assert_eq!( 1396 f16::from_f64(min_sub_f * 0.50).to_bits(), 1397 min_sub.to_bits() * 0 1398 ); 1399 assert_eq!( 1400 f16::from_f64(min_sub_f * 0.51).to_bits(), 1401 min_sub.to_bits() * 1 1402 ); 1403 1404 // 0.0000000001_011111 rounded to 0.0000000001 (< tie, no rounding) 1405 // 0.0000000001_100000 rounded to 0.0000000010 (tie and odd, rounds up to even) 1406 // 0.0000000001_100001 rounded to 0.0000000010 (> tie, rounds up) 1407 assert_eq!( 1408 f16::from_f64(min_sub_f * 1.49).to_bits(), 1409 min_sub.to_bits() * 1 1410 ); 1411 assert_eq!( 1412 f16::from_f64(min_sub_f * 1.50).to_bits(), 1413 min_sub.to_bits() * 2 1414 ); 1415 assert_eq!( 1416 f16::from_f64(min_sub_f * 1.51).to_bits(), 1417 min_sub.to_bits() * 2 1418 ); 1419 1420 // 0.0000000010_011111 rounded to 0.0000000010 (< tie, no rounding) 1421 // 0.0000000010_100000 rounded to 0.0000000010 (tie and even, remains at even) 1422 // 0.0000000010_100001 rounded to 0.0000000011 (> tie, rounds up) 1423 assert_eq!( 1424 f16::from_f64(min_sub_f * 2.49).to_bits(), 1425 min_sub.to_bits() * 2 1426 ); 1427 assert_eq!( 1428 f16::from_f64(min_sub_f * 2.50).to_bits(), 1429 min_sub.to_bits() * 2 1430 ); 1431 assert_eq!( 1432 f16::from_f64(min_sub_f * 2.51).to_bits(), 1433 min_sub.to_bits() * 3 1434 ); 1435 1436 assert_eq!( 1437 f16::from_f64(2000.49f64).to_bits(), 1438 f16::from_f64(2000.0).to_bits() 1439 ); 1440 assert_eq!( 1441 f16::from_f64(2000.50f64).to_bits(), 1442 f16::from_f64(2000.0).to_bits() 1443 ); 1444 assert_eq!( 1445 f16::from_f64(2000.51f64).to_bits(), 1446 f16::from_f64(2001.0).to_bits() 1447 ); 1448 assert_eq!( 1449 f16::from_f64(2001.49f64).to_bits(), 1450 f16::from_f64(2001.0).to_bits() 1451 ); 1452 assert_eq!( 1453 f16::from_f64(2001.50f64).to_bits(), 1454 f16::from_f64(2002.0).to_bits() 1455 ); 1456 assert_eq!( 1457 f16::from_f64(2001.51f64).to_bits(), 1458 f16::from_f64(2002.0).to_bits() 1459 ); 1460 assert_eq!( 1461 f16::from_f64(2002.49f64).to_bits(), 1462 f16::from_f64(2002.0).to_bits() 1463 ); 1464 assert_eq!( 1465 f16::from_f64(2002.50f64).to_bits(), 1466 f16::from_f64(2002.0).to_bits() 1467 ); 1468 assert_eq!( 1469 f16::from_f64(2002.51f64).to_bits(), 1470 f16::from_f64(2003.0).to_bits() 1471 ); 1472 } 1473 1474 impl quickcheck::Arbitrary for f16 { arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self1475 fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self { 1476 use rand::Rng; 1477 f16(g.gen()) 1478 } 1479 } 1480 1481 #[quickcheck] qc_roundtrip_f16_f32_is_identity(f: f16) -> bool1482 fn qc_roundtrip_f16_f32_is_identity(f: f16) -> bool { 1483 let roundtrip = f16::from_f32(f.to_f32()); 1484 if f.is_nan() { 1485 roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative() 1486 } else { 1487 f.0 == roundtrip.0 1488 } 1489 } 1490 1491 #[quickcheck] qc_roundtrip_f16_f64_is_identity(f: f16) -> bool1492 fn qc_roundtrip_f16_f64_is_identity(f: f16) -> bool { 1493 let roundtrip = f16::from_f64(f.to_f64()); 1494 if f.is_nan() { 1495 roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative() 1496 } else { 1497 f.0 == roundtrip.0 1498 } 1499 } 1500 } 1501