Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^2: [Study]: Searching for square roots

by Limbic~Region (Chancellor)
on Nov 14, 2006 at 21:21 UTC ( [id://584072]=note: print w/replies, xml ) Need Help??


in reply to Re: [Study]: Searching for square roots
in thread [Study]: Searching for square roots

roboticus,
Removing a node's content is generally frowned upon regardless of correctness. It is best to strike what is wrong or add an update then to remove it entirely. People do learn from other's mistakes.

FWIW, here is my take without having looked any other solutions to include monsieur_champs'.

print sqrt($_), "\t", mysqrt($_, .0000001), "\n" for qw/.25 .50 .75 1 +10 50 100 1000 31415926/; sub mysqrt { my ($tgt, $err, $try, $len) = @_; return 1 if $tgt == 1; if (! defined $try) { ($len, $try) = $tgt < 1 ? ((1 - $tgt) / 2, $tgt + (1 - $tgt) / 2) : ($tgt / 2, $tgt / 2); return mysqrt($tgt, $err, $try, $len); } my $dif = $tgt - ($try * $try); return $try if abs($dif) < $err; $len /= 2; $try = $dif > 0 ? $try + $len : $try - $len; return mysqrt($tgt, $err, $try, $len); }
If it isn't obvious, it is a binary search.

Update: The adjustment for values < 1 can be mathematically simplified. Additionally, a much faster converging algorithm would be $try = (($tgt / $try) + $try) / 2.

Cheers - L~R

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://584072]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (11)
As of 2024-04-18 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found