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