Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Pack samples with Float16Array and Math.f16round

Halve a Float32Array backing buffer with Float16Array and check rounding, underflow, and overflow before converting your data.

You have a million normalized samples in a Float32Array and want to keep another copy in memory. Storing the copy in half precision cuts the backing buffer from four million bytes to two million. First, check how much the values change.

Preview the rounding

Math.f16round() gives you the number you would read after rounding a value to IEEE 754 binary16. It returns a JavaScript number. To save memory, store the values in a Float16Array.

const samples = new Float32Array([1, 0.1, 0.5])
const packed = new Float16Array(samples)

console.log(samples.byteLength, packed.byteLength)
console.log(packed[1], Math.f16round(samples[1]))

The two buffers use 12 and 6 bytes, and both values on the second line are 0.0999755859375.

The constructor copies and converts each element. During conversion both buffers occupy memory. The saving applies once you can release the source array and keep the packed one. If you control the producer, allocate a Float16Array up front and store into it as samples arrive.

Check your error budget

Compare the rounded values with your inputs before changing the storage type. The total error a downstream calculation can tolerate depends on how it uses the samples. Use absolute error if a fixed deviation is acceptable. Compare relative error when the same deviation matters more for small nonzero values.

const inputs = [0.1, 0.5, 1, 1e-9, 70_000]
for (const input of inputs) {
  const rounded = Math.f16round(input)
  console.log(input, rounded, Math.abs(rounded - input))
}

You can see 0.5 and 1 survive intact, 1e-9 round to zero, and 70_000 overflow to Infinity.

Check the errors on values from your own dataset, including samples near any cutoff your code uses. A value can cross a cutoff after rounding even when the error seems small. For code that depends on very small nonzero values or finite values outside binary16's range, retain a wider format.

Feature-detect the constructor and Math.f16round before running these examples. Node 22 lacks both, so use a browser that implements them or a newer Node version. Keep the wider buffer on the fallback path and budget for its full byte length there.