Legitimate use of calling a sub as &sub

R

Richard Gration

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;
}
 
B

Brian McCauley

Richard said:
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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top