如何在JavaScript中近似计算浮点数的平方根

3

我想近似计算这个函数的平方根。Math.sqrt(float); 结果应该是另一个浮点数,小数点后最多有6或7位。 使用标准的Math.sqrt(float),我得到了一个非常大的数字,比如0.343423409554534598959,对我来说太多了。


4
将结果四舍五入到适当的位数即可。这比编写自己的近似值要快得多,并且出现错误的可能性更小。 - user85109
3个回答

6

如果您只想得到一个更小且更易管理的数字,可以使用toFixed方法,如下所示:

var x = 0.343423409554534598959;
console.log( x.toFixed(3) )
// outputs 0.343

如果你不想计算完整的平方根,只是想舍弃掉一些数字精度,那么可以使用近似方法。不过要注意,过早优化是万恶之源;而KISS原则与此相反。

这里介绍Heron's方法:

function sqrt(num) {
  // Create an initial guess by simply dividing by 3.
  var lastGuess, guess = num / 3;

  // Loop until a good enough approximation is found.
  do {
    lastGuess = guess;  // store the previous guess

    // find a new guess by averaging the old one with
    // the original number divided by the old guess.
    guess = (num / guess + guess) / 2;

  // Loop again if the product isn't close enough to
  // the original number.
  } while(Math.abs(lastGuess - guess) > 5e-15);

  return guess;  // return the approximate square root
};

更多的情况下,从这个维基百科页面实现一个平方根计算器应该是非常简单的。

这个第二个sqrt函数并不是一个sqrt函数,而实际上是一个舍入函数。一开始这让我非常困惑,直到我仔细阅读代码后意识到它根本没有试图计算sqrt!你可能考虑更改第二个方法的名称。 - Alex Pritchard
1
@AlexPritchard 你说得对!我删除了整个函数,因为它在这里没有特定的价值... - Yatharth Agarwal

0
在浏览stackoverflow时,我一段时间前发现了这段代码,它可以近似到所需的精度(这段代码不是我的,我只是复制粘贴)。
function round (value, precision, mode)
{
    precision |= 0; // making sure precision is integer
    var m = Math.pow(10, precision);
    value *= m;
    var sgn = (value > 0) | - (value < 0); // sign of the number
    var isHalf = value % 1 === 0.5 * sgn;
    var f = Math.floor(value);

    if (isHalf)
        switch (mode) {
            case 'PHP_ROUND_HALF_DOWN':
                value = f + (sgn < 0); // rounds .5 toward zero
                break;
            case 'PHP_ROUND_HALF_EVEN':
                value = f + (f % 2 * sgn); // rouds .5 towards the next even integer
                break;
            case 'PHP_ROUND_HALF_ODD':
                value = f + !(f % 2); // rounds .5 towards the next odd integer
                break;
            default:
                value = f + (sgn > 0); // rounds .5 away from zero
        }

    return (isHalf ? value : Math.round(value)) / m;
}

0
我们可以通过以下方式对平方根进行四舍五入:
(double)Math.round(float * Math.pow(10,r)) /Math.pow(10,r); 

其中,r 是我们想要在小数点后打印的数字。

尝试像这样编写程序

    float f = 0.123f;   
    double d = Math.sqrt(f);
    d = (double)Math.round(d * Math.pow(10,5)) /Math.pow(10,5); 
    System.out.println(d);

输出:0.35071


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接