You might also try this :
sub Root2 {
my $num = shift;
my $root = shift;
my $iterations = shift || 10;
if ( $root == 0 ) { return 1 }
if ( $num < 0 ) { return undef }
my $current = Math::BigFloat->new();
my $guess = Math::BigFloat->new( $num / $root );
my $t=Math::BigFloat->new($guess**($root-1)); 1st version : WRONG ! sh
+ould be in the loop.
for ( 1 .. $iterations ) {
$current = $guess - ( $guess * $t - $num ) / ( $root * $t );
if ( $guess eq $current ) { last }
$t=Math::BigFloat->new($current**($root-1));
$guess = $current;
}
return $current;
}
The idea behind, is that '**' is MUCH slower than '*', so I exchange 2 '**' for one '**' and 2 '*'
It
seems indeed to speed things alot :
(I'm sure your numerous tests will make it sure ;-)
timethese(10,{
'Root'=> sub {Root(1000,60)},
'Root2'=> sub {Root2(1000,60)}});
gives as result :
Benchmark: timing 10 iterations of Root, Root2...
Root: 104 wallclock secs (104.38 usr + 0.01 sys = 104.39 CPU) @
0.10/s (n=10)
Root2: 15 wallclock secs (14.75 usr + 0.00 sys = 14.75 CPU) @ 0.68/s (n=10)
Root2: 97 wallclock secs (92.67 usr + 0.16 sys = 92.83 CPU) @
0.11/s (n=10)
UPDATE :
Corrected my code! I misplaced the $t calculation outside the loop,
which is wrong beccause $guess change inside the loop.
As you can see it's no more so fast...
"
Only
Bad
Coders
Code
Badly
In
Perl" (OBC2BIP)
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.