← 中文资源

简体中文版本

Float16Array 半精度存储

Float16Array 每个值只占 2 字节:网格上的值(1、1.5、24.75)精确往返,0.3333 落到最近的半精度格点,65505–65519 舍回最大有限值 65504,≥65520 才溢出为 Infinity。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

byte length: 12 for 6 values
exact roundtrip: true true
0.3333 -> 0.333251953125
100000 -> Infinity (f16 max is 65504)
65519 -> 65504
1.5 bits are 0x3e00: true
NaN stays NaN: true
two bytes per value: true

实现说明

readings、half、bytes 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 每一步打印都带着自己的标签:byte length:、exact roundtrip:、0.3333 ->。

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件的状态由几个模块级绑定持有:readings、half、bytes。

核心语句

const readings = [1.0, 1.5, 24.75, 0.3333, 65519, 100000];
const bytes = new Uint8Array(half.buffer);
const half = new Float16Array(readings);

代码示例

// Float16Array storage: half-precision floats use 2 bytes per value instead
// of 4, trading precision for size (10-bit mantissa keeps ~3 decimal digits)
const readings = [1.0, 1.5, 24.75, 0.3333, 65519, 100000];
const half = new Float16Array(readings);

console.log("byte length:", half.byteLength, "for", readings.length, "values");
console.log("exact roundtrip:", half[0] === 1, half[2] === 24.75);
console.log("0.3333 ->", half[3]);
console.log("100000 ->", half[5], "(f16 max is 65504)");
console.log("65519 ->", half[4]);

// 1.5 occupies bits 0x3e00 in half precision
console.log("1.5 bits are 0x3e00:", new Uint16Array(half.buffer)[1] === 0x3e00);

// NaN propagates through half precision too
half[5] = Number.NaN;
console.log("NaN stays NaN:", Number.isNaN(half[5]));

const bytes = new Uint8Array(half.buffer);
console.log("two bytes per value:", bytes.length === readings.length * 2);