function NativeCalculator::sqrt
Adapted from https://cp-algorithms.com/num_methods/roots_newton.html
Overrides Calculator::sqrt
File
-
vendor/
brick/ math/ src/ Internal/ Calculator/ NativeCalculator.php, line 244
Class
- NativeCalculator
- Calculator implementation using only native PHP code.
Namespace
Brick\Math\Internal\CalculatorCode
public function sqrt(string $n) : string {
if ($n === '0') {
return '0';
}
// initial approximation
$x = \str_repeat('9', \intdiv(\strlen($n), 2) ?: 1);
$decreased = false;
for (;;) {
$nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2');
if ($x === $nx || $this->cmp($nx, $x) > 0 && $decreased) {
break;
}
$decreased = $this->cmp($nx, $x) < 0;
$x = $nx;
}
return $x;
}