简体   繁体   English

Javascript:这是真正签名的整数除法吗

[英]Javascript: Is This Truly Signed Integer Division

Given the following code, where both a and b are Number s representing values within the range of signed 32-bit signed integers: 给定以下代码,其中ab均为Number表示有符号32位有符号整数范围内的值:

var quotient = ((a|0) / (b|0))|0;

and assuming that the runtime is in full compliance with the ECMAScript 6 specifications, will the value of quotient always be the correct signed integer division of a and b as integers? 并假设运行时完全符合ECMAScript 6规范, quotient的值将始终ab作为整数的正确有符号整数除法吗? In other words, is this a proper method to achieve true signed integer division in JavaScript that is equivalent to the machine instruction? 换句话说,这是在JavaScript中实现与机器指令等效的真正有符号整数除法的正确方法吗?

I'm no expert on floating-point numbers, but Wikipedia says that doubles have 52 bits of precision. 我不是浮点数专家,但Wikipedia表示,双精度数具有52位精度。 Logically, it seems that 52 bits should be enough to reliably approximate integer division of 32-bit integers. 从逻辑上讲,看来52位应该足以可靠地近似32位整数的整数除法。

Dividing the minimum and maximum 32-bit signed ints, -2147483648 / 2147483647 , produces -1.0000000004656613 , which is still a reasonable amount of significant digits. 将最小和最大32位有符号整数-2147483648 / 2147483647会产生-1.0000000004656613 ,这仍然是一个合理数量的有效数字。 The same goes for its inverse, 2147483647 / -2147483648 , which produces -0.9999999995343387 . 其逆2147483647 / -2147483648 ,其产生-0.9999999995343387

An exception is division by zero , which I mentioned in a comment. 除以零是一个例外,我在评论中提到过。 As the linked SO question states, integer division by zero normally throws some sort of error, whereas floating-point coercion results in (1 / 0) | 0 == 0 如链接的SO问题所述,整数除以零通常会引发某种错误,而浮点强制会导致(1 / 0) | 0 == 0 1/0 (1 / 0) | 0 == 0 (1 / 0) | 0 == 0 . (1 / 0) | 0 == 0

Update: According to another SO answer , integer division in C truncates towards zero, which is what |0 does in JavaScript. 更新:根据另一个SO答案 ,C中的整数除法将截断为零,这就是JavaScript中|0作用。 In addition, division by 0 is undefined, so JavaScript is technically not incorrect in returning zero. 另外,除数0是不确定的,因此从技术上讲,JavaScript在返回零方面不是不正确的。 Unless I've missed anything else, the answer to the original question should be yes. 除非我没有其他任何遗漏,否则原始问题的答案应该是。

Update 2: Relevant sections of the ECMAScript 6 spec: how to divide numbers and how to convert to a 32-bit signed integer , which is what |0 does . 更新2: ECMAScript 6规范的相关部分:如何对数字进行除法以及如何将其转换为32位带符号整数|0就是这样做的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM