Yep, your initial guess doesn't work for $x < 1. I suggest just starting out with 1 instead:
sub sqrt ($) { my $x = shift; return sqrt_search( $x, 0, $x, 1, 50); } # Tests sub test { my $n = shift; print "SQRT $n: ", &sqrt( $n ), ' ?= ', eval { CORE::sqrt( $n ) } +, $/, $/; } test( $_ ) for( 16, 9, 4, 2, 0.5, -1, 0, 0.001 );
Output:
SQRT 16: 4.0000114440918 ?= 4 SQRT 9: 3 ?= 3 SQRT 4: 1.99998474121094 ?= 2 SQRT 2: 1.4141845703125 ?= 1.4142135623731 SQRT 0.5: 0.7071533203125 ?= 0.707106781186548 SQRT -1: ?= SQRT 0: 0.0078125 ?= 0 SQRT 0.001: 0.03125 ?= 0.0316227766016838

In reply to Re: [Study]: Searching for square roots by rhesa
in thread [Study]: Searching for square roots by monsieur_champs

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.