# cubic root subroutine - Page 2

•  Subject
• Author
• Posted on

## Re: cubic root subroutine

On Sat, 19 Feb 2005 21:37:11 +0000, Dan van Ginhoven wrote:

> Hi.
>
> I needed a cubic root subroutine but didnīt find one at a quick search.
> So I wrote a simple one.
> It seems pretty fast and accurate enough.
> Any ideas  how to improve it,
> or point me to better solutions.
> /dg
>
<SNIP>

Here's one using Newton-Raphson:
(http://www.sosmath.com/calculus/diff/der07/der07.html )

#!/usr/bin/perl

use strict;
use warnings;

# Program to find the cubic root of a number using the Newton-Raphson
#   method for approximating the roots of polynomials
#
# Here, f(x) = x**3 - n where n is the number to be rooted
# thus f'(x) = 3x**2
#
# [ f'(x) is the first differential of f(x) wrt x ]

my \$findcubicrootof = \$ARGV[0] || 27;
my \$first_guess = \$findcubicrootof / 3;
my \$accuracy = 0.000000000000001;

# Arbitrarily set to what works on my machine. YMMV
die "Accuracy exceeds machine limits\n" if (\$accuracy < 1e-15);

print "The cubic root of \$findcubicrootof is ",
nr(\$first_guess,\$findcubicrootof,\$accuracy),
" +/- \$accuracy\n";

sub nr {
my (\$guess,\$n,\$accuracy) = @_;

# Find delta
my \$delta = fofx(\$guess,\$n) / fdashofx(\$guess,\$n);

if (abs(\$delta) < \$accuracy) {
return \$guess;
} else {
return nr(\$guess - \$delta,\$n,\$accuracy);
}
}

# Returns f(x)
sub fofx {
my (\$x,\$n) = @_;
return \$x ** 3 - \$n;
}

# Returns f'(x)
sub fdashofx {
my (\$x,\$n) = @_;
return 3 * \$x ** 2;
}