Math.sqrt() vs. Newton Raphson Method

Benchmark created by Rob Ede on


Description

A comparison against the built-in Math.sqrt(n) and root(n), a function that computes the square root of n using the Newton Raphson Method.

Test runner

Ready to run.

Testing in
TestOps/sec
Math.sqrt
for (var n = 1; n < 100; n++) {
  Math.sqrt(n);
}
ready
root
for (var n = 1; n < 100; n++) {

  if (n == 0) return 0;
  if (n < 0) return NaN;
  var itts = 1000;
  var xb2, xb1;
  var x0 = 1;
  x0 = n < 1 ? n * 100 : n / 100;
  var i;
  for (i = 0; i < itts; i++) {
    xb2 = xb1;
    xb1 = x0;
    var xn = x0 - ((x0 * x0 - n) / (2 * x0));
    if (xn == xb1) {
      break;
    }
    if (xn == xb2) {
      x0 = (xb1 + xb2) / 2;
      break;
    }
    x0 = xn;
  }

}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.