sha*_*unc 12 javascript bigint
事实证明(外部有点想法它更明显,但无论如何)BigInt最近引入 javascript 有一个限制:
我的问题是 - 是否有类似于Number.MAX_SAFE_INTEGERBigInt的常量?
这段代码:
let a = 2n, step = 1;
try{while(true) {
console.log(step);
a=a**2n; step++
}} catch(e){ console.log(e)}
Run Code Online (Sandbox Code Playgroud)
显示该限制大约为 (step = 32) - 至少在 Chrome 中。但我想知道根据规范这个值是多少。
webkit 中 BigInt 的最大大小是这样定义的
// The maximum length that the current implementation supports would be
// maxInt / digitBits. However, we use a lower limit for now, because
// raising it later is easier than lowering it.
// Support up to 1 million bits.
static constexpr unsigned maxLength = 1024 * 1024 / (sizeof(void*) * bitsPerByte);
Run Code Online (Sandbox Code Playgroud)
void* 的大小取决于平台,在 64 位系统上为 8。
那么你的答案就对了吗?应该是 16384 位....(-1 表示符号)。但我无法在控制台中创建接近那么大的数字。
似乎根据规范对 BigInt 没有最大限制,考虑到 BigInts 应该是任意精度整数,其“精度位数仅受主机系统可用内存的限制” ,这是有道理的。
具体到 v8,根据v8 博客上的这篇文章,BigInts 的精度是“任意达到一个实现定义的限制”。不幸的是,我找不到有关如何确定限制的任何进一步信息。也许其他人能够根据这些v8 BigInt 实现说明对此有所了解?
也就是说,根据上述文章,BigInt 似乎没有特定的最大值/大小。相反,它很可能以某种方式基于系统上的可用内存来确定。
事实证明它是2^30 - 1位,即 2^(2^30) - 1。再多的位就不起作用了。(我无法获得实际值,因为位移不能做到这一点)相比之下,该数字的位数比美国的人口还要多(几乎是美国人口的两倍)!
在现代 Chrome 浏览器上进行了测试。
不过,奇怪的是,根据4.3.25BigInt value ,大小具有任意精度,在20.2 BigInt 对象部分中没有提及。
这是一个快速测试程序:
/* global BigInt */
let b = BigInt(10)
let exp = 1;
while (true) {
console.log(`BigInt of 10^${exp} `);
b = b * b;
exp *= 2;
}
Run Code Online (Sandbox Code Playgroud)
Node v13.2 的输出:
BigInt of 10^1
BigInt of 10^2
BigInt of 10^4
...
BigInt of 10^4194304
BigInt of 10^8388608
BigInt of 10^16777216
Run Code Online (Sandbox Code Playgroud)
在大约十到百万分之一之后,性能确实很慢。
虽然特定浏览器中可能存在特定于平台的最大值,但显示它的大小要求会很大。即使是 10^10^6 也需要超过 300K 来存储。您可以扩展规范以使用Tetration添加限制,例如“限制约为 10^10^10^... 8 次”,但是,说真的,这很愚蠢。