Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. NativeCalculator.php

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\Calculator

Code

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;
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal