Modules

Float16

moduleSource

Available on macOS, Linux, Windows, Wasm

#import "Float16";

The 16-bit IEEE half-precision storage format, with conversions to and from float32 and the Math vector and matrix types.

A Float16 holds only the bits (1 sign, 5 exponent, 10 significand) and has no arithmetic: convert to float32 with float16_to_float32, compute, and convert back with float32_to_float16. Halves have about three decimal digits and top out at 65504.

Example↗
half := float32_to_float16(1.5);
assert(float16_to_float32(half) == 1.5);

Module parameters#

ASSERT_ON_OVERFLOW := false
Fails an assert when a finite value is too large for a half, instead of making it infinity.

Procedures#

(_f: float32) -> Float16

Converts a float32 to the nearest half, rounding ties to even.

assert(cast(u16) float_to_half_fast3(1.0) == 0x3c00);
assert(cast(u16) float_to_half_fast3(-2.0) == 0xc000);
assert(cast(u16) float_to_half_fast3(65504.0) == 0x7bff);
assert(cast(u16) float_to_half_fast3(1.0 / 3.0) == 0x3555);
assert(cast(u16) float_to_half_fast3(100000.0) == 0x7c00); // overflow: infinity
assert(cast(u16) float_to_half_fast3(cast(float32) 1.00048828125) == 0x3c00); // tie rounds to even
↗

Types#

:: #type,isa u16

A half-precision float stored as 16 bits. It is distinct from u16, so it cannot be mixed with integers by accident; cast(u16) h gives the raw bits and cast(Float16) bits builds one from them.

one := float32_to_float16(1.0);
assert(cast(u16) one == 0x3c00);
assert(float16_to_float32(cast(Float16) 0x4000) == 2.0);
↗