Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript大整数平方根_Javascript_Node.js_Bigint - Fatal编程技术网

JavaScript大整数平方根

JavaScript大整数平方根,javascript,node.js,bigint,Javascript,Node.js,Bigint,这与Chrome和Node v10.4中支持的新JavaScript BigInt类型有关 以下两行都会引发错误: Math.sqrt(9n) Math.sqrt(BigInt(9)) 错误是: 无法将BigInt值转换为数字 如何在JavaScript中获取BigInt的平方根?TIA从这里开始: 函数sqrt(值){ 如果(值1n; 如果(x0==x1 | | x0==(x1-1n)){ 返回x0; } 返回牛顿公式(n,x1); } 返回牛顿数(值,1n); } sqrt(BigInt(

这与Chrome和Node v10.4中支持的新JavaScript BigInt类型有关

以下两行都会引发错误:

Math.sqrt(9n)
Math.sqrt(BigInt(9))
错误是:

无法将BigInt值转换为数字

如何在JavaScript中获取BigInt的平方根?TIA从这里开始:

函数sqrt(值){
如果(值<0n){
抛出“不支持负数的平方根”
}
if(值<2n){
返回值;
}
函数牛顿化(n,x0){
常数x1=((n/x0)+x0)>>1n;
如果(x0==x1 | | x0==(x1-1n)){
返回x0;
}
返回牛顿公式(n,x1);
}
返回牛顿数(值,1n);
}
sqrt(BigInt(9))

以下是更通用的解决方案

函数rootNth(val,k=2n){
设o=0n;//旧近似值
设x=val;
设极限=100;
while(x**k!==k&&x!==o&&--limit){
o=x;
x=((k-1n)*x+val/x**(k-1n))/k;
}
返回x;
}
设v=10000000000n;
log(`root^3 form${v.toString()}=${rootNth(v,3n.toString()}`)有一个npm库,似乎工作正常。如果没有整数根,则返回下限值

const sqrt = require('bigint-isqrt');
> sqrt(1023n);
31n
> sqrt(1024n);
32n

虽然对于我来说,像
value<16n
1n这样的神奇数字如何用于初始猜测(将
1n
传递给
newtonIteration
的第一个调用)仍然是个谜,但最好使用
const guess=1n+(sqrt(value>>BigInt(Math.floor(bitLength(value)/2))之类的东西不幸的是,这只适用于整数平方根。仅供参考,传入
4n
似乎会给出
1n
,而不是
2n
。似乎是迭代偏差导致了这一点,即
x0==(x1-1n)
。这似乎是唯一的错误情况;因此,为它添加一个额外的特殊情况就足够了。如果此函数执行的次数超过
限制
迭代次数,则返回错误结果。它最好抛出一个错误。
const sqrt = require('bigint-isqrt');
> sqrt(1023n);
31n
> sqrt(1024n);
32n