# Newton's Square Root Method

A very simple implementation for Newton's square root approximation method.
It isn't foolproof (as in I haven't fully tested it), but it seems to work.
Initial guess calculation adapted from here.

```import cpp.Lib;

/**
*  A square root approximator.
*
*  This program is free software: you can redistribute it and/or modify
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*  @author lemon42
*/

class SquareRoot {
static function main() {
var x:Float = 123456789;
Sys.println("Square root of " + x + ": " + newton(x));
}

static function average(a:Float, b:Float):Float {
return (a + b) / 2.0;
}
static function improve(guess:Float, x:Float):Float {
return average(guess, x / guess);
}

static function newton(x:Float) {
var guess:Float = x;

//Calculate inital guess
var val = 0;
while (guess >= 100) {
guess /= 10;
val++;
}

if (guess < 10) {
guess = 2 * Math.pow(10, Math.floor(val / 2));
} else {
guess = 6 * Math.pow(10, Math.floor(val / 2));
}

//Start improving estimation
while (Math.abs(guess * guess - x) >= 0.0001)
guess = improve(guess, x);

return guess;
}
}```

Example output:

`Square root of 123456789: 11111.11106`

version #19929, modified 2014-02-06 01:31:13 by lemon42