Skip to content

Instantly share code, notes, and snippets.

@Moligaloo
Created January 25, 2021 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Moligaloo/42ec0b841b7234867db5b78fc1832589 to your computer and use it in GitHub Desktop.
Save Moligaloo/42ec0b841b7234867db5b78fc1832589 to your computer and use it in GitHub Desktop.
Find square root by dichotomy and newton iteration
class Main {
public static function main() {
trace(dichotomySqrt(2));
trace(newtonSqrt(2));
}
static function dichotomySqrt(x:Float):Float {
if (x < 0) {
return Math.NaN;
}
if (x == 1 || x == 0) {
return x;
}
var L = 0.0;
var R = Math.max(x, 1);
while (true) {
final guessed = (L + R) / 2;
final squared = guessed * guessed;
if (Math.abs(squared - x) < 1e-6) {
return guessed;
}
if (squared > x) {
R = guessed;
} else {
L = guessed;
}
}
}
static function newtonSqrt(x:Float):Float {
if (x < 0) {
return Math.NaN;
}
if (x == 1 || x == 0) {
return x;
}
var r = 1.0;
while (Math.abs(r * r - x) > 1e-6) {
r = (x / r + r) / 2;
}
return r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment