Hi all,
Below is a program to calculate the cubic root of a number by
NewtonRaphson which I knocked up to post to the "cubic root subroutine"
thread below. I noticed that the nr function passed 2 of its 3 arguments
unchanged when it recursed. It occured to me that this might be a
legitimate use of using &nr to recurse, having altered the one argument in
@_ which did change. I was just wondering if this is bad style, because I
changed @_, or if it is acceptable ... any comments anyone?
Rich
#!/usr/bin/perl
use strict;
use warnings;
# Program to find the cubic root of a number using the NewtonRaphson
# 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.00000001;
# Arbitrarily set to what works on my machine. YMMV
die "Accuracy exceeds machine limits\n" if ($accuracy < 1e15);
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 {
$_[0] = $_[0]  $delta;
return &nr;
}
}
# Returns f(x)
sub fofx {
my ($x,$n) = @_;
return $x ** 3  $n;
}
# Returns f'(x)
sub fdashofx {
my ($x,$n) = @_;
return 3 * $x ** 2;
}
