I decided to roll my own mathematical algorithm---my first---just for kicks. The code below finds the square root of a positive number. My code looks/feels very kludgy and I'm curious to see how a pro would tackle this problem. So if you have a minute, please take a look. One part of the code that is really lacking is that one of the subroutines, namely newguess(), is actually run twice for each iteration. How can this be avoided without using global variables?
For those who are like me and are not math geniuses, you calculate a square root by dividing the radicand (the number you want to find the square root of) by an initial guess, Guess A, and then averaging the result of that division with Guess A to get a new guess, Guess B, which is then divided into the radicand and averaged with the result of that division and Guess B to yield Guess C, etc. etc.
So, for example, if you wanted to find the sqaure root fo 2 and your initial guess is 1:
OK, here's the code...2 / 1 = 2 (2 + 1) / 2 = 1.5 2 / 1.5 = 1.333333 (1.333333 + 1.5) / 2 = 1.4167 2 / 1.4167 = 1.4118 ( 1.4167 / 1.4118 ) / 2 = 1.4142 etc. The more times you perform the above procedure, the more accurate your + answer.
#!/usr/bin/perl -w use strict; while (<STDIN>) { # GET INPUT FROM COMMAND LINE chomp; $_ > 0 && ( /^\d*\.\d+$/ ) && last; # ASK AGAIN UNLESS VALID INPUT + GIVEN print "Please enter a positive number only!\n"; } sqroot(1, $_); # PASS INITIAL GUESS OF '1' AND RADICAND TO SQROOT SUB sub sqroot { my ($guess, $x) = @_; while ( get_accuracy($guess, new_guess($guess, $x)) > .0000000000 +00000001) { # CHECK DIFFERENCE BETWEEN OLD GUESS AND NEW GUESS $guess = new_guess($guess, $x); # MAKE OLD GUESS THE NEW GUESS + AND RUN WHILE LOOP AGAIN } print $guess; # PRINT GUESS IF (OLD GUESS - NEW GUESS) IS VERY CLO +SE } sub new_guess { # REFINE THE OLD GUESS TO MAKE MORE ACCURATE my ($guess, $x) = @_; my $x_div_guess = $x / $guess; # DIVIDE RADICAND BY OLD GUESS return ($guess + $x_div_guess) / 2; # RETURN, AS NEW GUESS, THE AV +ERAGE OF OLD GUESS AND RADICAND DIVIDED BY OLD GUESS } sub get_accuracy { my ($guess, $newguess) = @_; return (abs ($guess - $newguess)); # COMPARES HOW CLOSE OLD GUESS +AND NEW GUESS ARE }
$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot";
$nysus = $PM . $MCF;
In reply to Square Root algorithm by nysus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |