note
Dominus
I was able to make your program a <i>lot</i>
faster with a simple change.
Newton's method tends to double the number of correct digits with each iteration.
If you get a good initial guess, the convergence is extremely fast.
But if you botch the initial guess, there are no correct digits.
Your initial guess was very bad:<p>
<code>
my $guess = Math::BigFloat->new( $num / $root );
</code>
Newton's method works by drawing a straight line, tangent to the
polynomial curve, at the point of the guess. For your
examples, your guess was much too big, so the straight line
was almost vertical. This means that the new guess wasn't
very far from the old one.<p>
I replaced this one line with the following:
<code>
my $guess = Math::BigFloat->new( $num**(1/$root));
</code>
This uses regular hardware floating-point arithmetic to make the initial guess.
Hardware floating point is accurate to 17 decimal places and
is almost instantaneous. Suddenly, the initial guess is
vastly more accurate, and the cost is almost zero.<p>
Suddenly, I was getting very accurate answers very quickly.
After 10 iterations, your version of the program still thinks that Root(1000,60) is
about 14.088. The correct answer is about 1.12; with my
change the program has the answer correct to 130 places after only 4 iterations.
<p>
I'd also recommend simplifying the guess computation as
suggested by [arhuman] above. I guess he made a simple mistake in the algebra.
But you have <i>g</i>-
(<i>g<sup>r</sup></i>-<i>n</i>)/<i>rg<sup>r-1</sup></i>,
and you can cancel the <i>g<sup>r</sup></i> out of the
numerator by rewriting this expression as
<i>g</i>-<i>g</i>/<i>r</i>+
<i>n</i>/<i>rg<sup>r-1</sup></i>. This trades a <tt>**</tt> for a
<tt>/</tt>, which should be a big win.<p>
Hope this helps.<p>
<p>
--<br><font size="-2">
<a href="mailto:mjd-www-perlmonks+@plover.com">Mark Dominus</a><br>
<a href="http://perl.plover.com">Perl Paraphernalia</a><br></font>
134419
134419