MakeJavaScript Math.sqrt()打印更多数字

问题描述 投票:0回答:3

如果我在html页面上写

document.write(Math.sqrt(2))
,我会得到
1.4142135623730951

有任何方法可以使该方法输出超过16个小数位?

javascript math.sqrt
3个回答
7
投票
要获得结果的更多数字,您将需要使用任意推荐的数学库。但是,我不知道支持方形根源的JavaScript中的任何一个 - 我能够找到副手(big.js)仅支持加法,减法和比较。

您可以使用

toPrecision

2
投票
。但是,ECMA仅重新汇编的精度最高21个重要数字:

console.log(Math.sqrt(2).toPrecision(21))


但请记住,计算机上真实值的精度具有一定的限制(请参阅duskwuff的答案

)。
也请参见:

toFixed

制作的代码

0
投票

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));

	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.