如果我在html页面上写
document.write(Math.sqrt(2))
,我会得到1.4142135623730951
。
有任何方法可以使该方法输出超过16个小数位?
您可以使用
toPrecision
console.log(Math.sqrt(2).toPrecision(21))
但请记住,计算机上真实值的精度具有一定的限制(请参阅duskwuff的答案)。
也请参见:
toFixed
toExponential
BigInt
function sqrt(x, p) {
x = BigInt(x);
p = BigInt(p);
let res = 10n ** (p + 2n);
function f(t) {
return t ** 2n / 10n ** p - x * 10n ** p;
};
function fprime(x) {
return 2n * x;
};
for (let i = 1; i <= 1000; i++) {
res = res - f(res) * 10n ** p / fprime(res);
};
res = String(res);
p = Number(p);
res1 = res.substring(1,res.length-(p+1));
res2 = res.substring(res.length-p,res.length);
return res1 + '.' + res2;
};
console.log(sqrt(2,1000));