Created
January 25, 2021 12:50
-
-
Save Moligaloo/42ec0b841b7234867db5b78fc1832589 to your computer and use it in GitHub Desktop.
Find square root by dichotomy and newton iteration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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