如何在javascript中近似浮点的平方根

Cla*_*aro 2 math

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

Yat*_*wal 5

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

var x = 0.343423409554534598959;
console.log( x.toFixed(3) )
// outputs 0.343
Run Code Online (Sandbox Code Playgroud)

如果你无法忍受计算整个平方根并且只是抛出精度数字的想法,你可以使用近似方法.但要注意,过早的优化是万恶之源; 并且KISS成语违背了这一点.

这是Heron的方法:

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
};
Run Code Online (Sandbox Code Playgroud)

更多信息,从Wikipedia页面实现一个应该是微不足道的.