Next Making Programs Faster 117

Numerical Calculation

        http://www.perlmonks.org/index.pl?node_id=134419


Good day, fellow monks. I've got a snippet of code that I'm hoping you can help me speed up. My code is to find the N-th root of a given number.

     use Math::BigFloat;

     sub Root {
         my $num        = shift;
         my $root       = shift;
         my $iterations = shift || 5;
         if ( $num < 0 ) { return undef }
         if ( $root == 0 ) { return 1 }
         my $Num = Math::BigFloat->new( $num );
         my $Root = Math::BigFloat->new( $root );
         my $current = Math::BigFloat->new();
         my $guess   = Math::BigFloat->new( $num / $root );
         my $t       = Math::BigFloat->new( $guess ** ( $root - 1 ) ); 
         for ( 1 .. $iterations ) {
             $current = $guess - ( $guess * $t - $Num ) / ( $Root * $t  );
             if ( $guess eq $current ) { last }
             $t = $current**($root-1);
             $guess = $current;
         }
         return $current;
     }


This uses Newton's method for finding the roots. It produces very accurate results, provided you increase the number of iterations if you're dealing with large numbers and/or large roots. Therein lies the problem.

Next Copyright © 2003 M. J. Dominus