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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.