I need some help. I'm trying to approximate the square roots of very large numbers. I wrote the code, but it isn't working right, so obviously I'm overlooking something. In brief, the method for approximating square roots works like this:
  1. Guess at the square root
  2. Divide the number you're trying to get the square root of by the number you just guessed.
  3. Add the quotient to your original guess and divide by 2.
  4. Treat this new number as your guess at the square root and go back to step #2.
Here's my original code:
use Math::BigFloat; sub SqrRoot { my $num = Math::BigFloat->new( shift ); my $iterations = shift || 50; my $guess = Math::BigFloat->new( $num / 2 ); for ( 1..$iterations ) { $guess = (( $num / $guess ) + $guess ) / 2; } return $guess; }
When I saw that this wasn't working, I broke the code down a little further to check the values during the whole process.
use Math::BigFloat; sub SqrRoot { my $num = Math::BigFloat->new( shift ); my $iterations = shift || 50; my $guess = Math::BigFloat->new( $num / 2 ); my $temp = Math::BigFloat->new(); for ( 1..$iterations ) { $temp = Math::BigFloat->new( $num / $guess ); print ("$num / $guess = $temp\n"); $temp += $guess; $guess = $temp / 2; print ("$guess\n----------\n"); } return $guess; }
In theory, this process should become more and more accurate, the more iterations it is run through. However, for reasons I don't know, the above code is dropping decimal places, and actually makes the result less accurate on each iteration. What am I missing?

Thanks in advance.
___________________
Kurt

In reply to Approximating Square Roots by sifukurt

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.