sifukurt has asked for the wisdom of the Perl Monks concerning the following question:
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 ); for ( 1..$iterations ) { $guess = (( $num / $guess ) + $guess ) / 2; } 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?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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Approximating Square Roots
by suaveant (Parson) on Oct 05, 2001 at 21:26 UTC | |
by sifukurt (Hermit) on Oct 05, 2001 at 21:36 UTC | |
by Anonymous Monk on Nov 25, 2001 at 20:44 UTC | |
|
Re: Approximating Square Roots
by cLive ;-) (Prior) on Oct 06, 2001 at 00:44 UTC |