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:
- Guess at the square root
- Divide the number you're trying to get the square root of by the number you just guessed.
- Add the quotient to your original guess and divide by 2.
- 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