Skip to content

Instantly share code, notes, and snippets.

@Angelfirenze
Forked from pbondoer/SquareRoot.hx
Created February 5, 2014 22:45
Show Gist options
  • Save Angelfirenze/8834889 to your computer and use it in GitHub Desktop.
Save Angelfirenze/8834889 to your computer and use it in GitHub Desktop.
package ;
import cpp.Lib;
import haxe.Int64;
/**
* A square root approximator.
*
* @author lemon42
*/
class Main
{
static var acc:Float = 0.00001;
static function main() {
var x:Float = 7777777777;
Sys.println("Square root of " + x);
Sys.println("Accuracy: " + acc);
Sys.println("");
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 check(guess:Float, x:Float):Bool {
return Math.abs(guess * guess - x) < acc;
}
static function newton(x:Float) {
var i = 0;
var guess:Float = x;
var start:Float = Sys.time();
//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 (!check(guess, x)) {
Sys.println(" Guess " + ++i + " --> " + guess);
guess = improve(guess, x);
}
Sys.println(" Guess " + ++i + " --> " + guess);
Sys.println("");
Sys.println("Guessed in " + i + " tries, " + (Sys.time() - start) + " secs");
Sys.println("");
return guess;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment