Next Tricks of the Wizards 159

Square Roots with Newton-Raphson Method

        sub square_root {
          my ($n, $e) = @_;       
          $e ||= 0.00001;
          my $guess = $n;    # Yes, just guess!
          while (abs(($guess*$guess - $n)/$n) > $e) {
            $guess = ($guess + $n/$guess)/2;
          }
          return $guess;
        }


Next Copyright © 2003 M. J. Dominus