Velocity Reviews > Perl > Legitimate use of calling a sub as &sub

# Legitimate use of calling a sub as &sub

Richard Gration
Guest
Posts: n/a

 02-23-2005
Hi all,

Below is a program to calculate the cubic root of a number by
Newton-Raphson 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 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.00000001;

# 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 {
\$_[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;
}

Brian McCauley
Guest
Posts: n/a

 02-23-2005

Richard Gration wrote:

> Below is a program to calculate the cubic root of a number by
> Newton-Raphson 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?

It is certainly questionable style. I've been known to do it but I
definitely feel dirty when I do so.

If you are going to modify @_ in this way you should get into the habit
of using shift/unshift or splice. Modifying \$_[0] directly modifies
the variable in the calling code. You probably don't want that.

Of course the particular example you give is pure tail recursion so is
better implemented as a loop (or even a goto).