in reply to Square Root algorithm

What about this?
#!/usr/bin/perl use strict; my ($guess,$num); # get number while(<STDIN>) { $guess = $num = $_+0; last if ($num>0); } # iterate until within 1e-13 # go further and you need some math module, I think :) while (abs($num - $guess**2) > 1e-13) { $guess = (($num/$guess) + $guess)/2; } # print our guess and what Perl says print "My guess of square root of $num is $guess\n"; print "Perl says it's ".$num**.5."\n";

cLive ;-)

PS - golf version? :)

#!/usr/bin/perl use strict; my $n; while(<STDIN>) { $n = $_+0; last if $n>0} while (abs($n - $_**2) > 1e-13){ $_ = ($n/$_ + $_)/2} print "Guess: $_\nperl: ".$n**.5."\n";

Replies are listed 'Best First'.
Re: Re: Square Root algorithm
by nysus (Parson) on Jun 25, 2001 at 11:59 UTC
    I tried your solution on very small numbers such as .000000000323 and the accuracy was way off. I believe it is because you compare the radicand to the square of the guess instead of comparing the last guess to the current guess. At any rate, that is a very short solution, for sure.

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot";
    $nysus = $PM . $MCF;

      yep,

      Sort of. I think I just mis-read my comparison (got confused coz I was using guess and next guess...)

      Change this:

      while (abs($num - $guess**2) > 1e-13) {
      to the more accurate comparison (with 2 more decimal places of accuracy):
      while (abs($num/$guess - $guess) > 1e-15) {
      and it works fine :)

      cLive ;-)