在 JavaScript 中使用 Atomics 和 Float32Array

use*_*048 3 javascript atomic typed-arrays

Atomics.store/load 方法(和其他方法?没看)不支持 Float32Array。我读到这是为了与以下事实相一致:出于兼容性原因,它也不支持 Float64Array(某些计算机不支持它)。

除了我认为这很愚蠢之外,这是否也意味着我必须将要使用的每个浮点数转换为无符号整数?

这不仅会导致代码丑陋,而且还会使其速度变慢。

例如:

let a = new Float32Array(1); // Want the result here

Atomics.store(a, 0, 0.5); // Oops, can't use Float32Array

let b = new Float32Array(1); // Want the result here

let uint = new Uint32Array(1);
let float = new Float32Array(uint.buffer);

float[0] = 0.5;

Atomics.store(b, 0, uint[0]);
Run Code Online (Sandbox Code Playgroud)

小智 6

正如您所发现的,Atomics 方法不支持浮点值作为参数:

Atomics.store(typedArray, 索引, 值)

typedArray
    共享整数类型数组。Int8Array、Uint8Array、Int16Array、Uint16Array、Int32Array 或 Uint32Array 之一
    。

您可以从底层缓冲区中读取 IEEE754 表示形式作为整数,就像在您发布的示例代码中所做的那样

var buffer = new ArrayBuffer(4);         // common buffer
var float32 = new Float32Array(buffer);  // floating point
var uint32 = new Uint32Array(buffer);    // IEEE754 representation

float32[0] = 0.5;
console.log("0x" + uint32[0].toString(16));

uint32[0] = 0x3f000000;   /// IEEE754 32-bit representation of 0.5
console.log(float32[0]);
Run Code Online (Sandbox Code Playgroud)

或者,如果准确性不重要,您可以使用固定数字。准确度当然是由大小决定的。

存储时按比例放大:

Atomics.store(a, 0, Math.round(0.5 * 100)); // 0.5 -> 50 (max two decimals with 100)
Run Code Online (Sandbox Code Playgroud)

回读并缩小:

value = Atomics.load(a, 0) * 0.01;          // 50 -> 0.5
Run Code Online (Sandbox Code Playgroud)