Code: Select all
function sqrt($num) {
// Returns the square root of a positive number in base 10.
// Any other argument causes the function to throw an error.
// The result has 10E-13 precision.
// Based on the Babylonian algorithm (see https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method).
//
// $num the positive number in base 10 to calculate the square root of
assert regexmatches("$num", "[^0-9.,]") == "", "Argument is not a positive number";
$num = eval($num);
$eps = eval(1/1000000000000);
if ($num >= 100) {
$root = $num/20;
} elseif ($num >= 2) {
$root = $num/2;
} elseif ($num >= 2/100) {
$root = $num;
} else {
$root = $num*10;
};
while (abs($root^2 - $num) > $eps) {
$root = ($root + $num/$root)/2;
};
return $root;
}
XYplorer Beta Club