实现说明
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);