dan*_*y74 9 javascript bigint node.js
这涉及 Chrome 和 Node v10.4 支持的新 JavaScript BigInt 类型
以下两行都抛出错误:
Math.sqrt(9n)
Math.sqrt(BigInt(9))
Run Code Online (Sandbox Code Playgroud)
错误是:
无法将 BigInt 值转换为数字
如何在 JavaScript 中获得 BigInt 的平方根?TIA
Ant*_*ton 11
从这里:https : //golb.hplar.ch/2018/09/javascript-bigint.html
function sqrt(value) {
if (value < 0n) {
throw 'square root of negative numbers is not supported'
}
if (value < 2n) {
return value;
}
function newtonIteration(n, x0) {
const x1 = ((n / x0) + x0) >> 1n;
if (x0 === x1 || x0 === (x1 - 1n)) {
return x0;
}
return newtonIteration(n, x1);
}
return newtonIteration(value, 1n);
}
sqrt(BigInt(9))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2813 次 |
| 最近记录: |