Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Created November 9, 2013 04:07
Show Gist options
  • Save animatedlew/7381483 to your computer and use it in GitHub Desktop.
Save animatedlew/7381483 to your computer and use it in GitHub Desktop.

Revisions

  1. animatedlew created this gist Nov 9, 2013.
    20 changes: 20 additions & 0 deletions sqrt.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    var sqrt = function(x) {
    var isGoodEnough = function(guess) {
    return Math.abs(guess * guess - x) / x < 0.001;
    };

    var improve = function(guess) {
    return (guess + x / guess) / 2;
    };

    var sqrIter = function(guess) {
    return (isGoodEnough(guess)) ? guess : sqrIter(improve(guess))
    };

    return sqrIter(1.0);
    };

    console.log(
    Math.sqrt(1000),
    sqrt(1000)
    );