← 中文资源

简体中文版本

imul 在 32 位回绕中相乘

Math.imul 做真正的 32 位整数乘法并按位回绕;普通 * 在双精度里继续放大、超过 2^53 后静默丢失低位,两者在大数上分道扬镳,小数则完全一致。

阅读英文原文

运行结果

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

plain multiply: 4122776541730331600
Math.imul     : -635020110
as unsigned hex: da265cb2
small inputs: 12 12
truncates operands: 2

使用要点

  • 跑完文件,输出里会留下标记——plain multiply:、as unsigned hex:、small inputs:。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。

核心语句

const a = 0xdeadbeef;
const b = 0x41c6ce6e;

代码示例

// Math.imul multiplies in true 32-bit space and wraps; plain * keeps
// going in double precision, so the two diverge past 2^53
const a = 0xdeadbeef;
const b = 0x41c6ce6e;

console.log('plain multiply:', a * b);
console.log('Math.imul     :', Math.imul(a, b));
console.log('as unsigned hex:', (Math.imul(a, b) >>> 0).toString(16));

// Both agree while the product still fits in double precision
console.log('small inputs:', Math.imul(3, 4), 3 * 4);

// Operands are truncated to 32-bit integers before multiplying
console.log('truncates operands:', Math.imul(1.9, 2.9));