Created
July 29, 2019 14:10
-
-
Save msouth/8e419fba776af300b2636901bf51b2f1 to your computer and use it in GitHub Desktop.
Watch Newton's method converge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my $square = shift or die "Usage: $0 3 [where 3 is the number you want to find the square root of]"; | |
my $guess; | |
"This is an implementation of Newton's method for finding roots. | |
(Specifically, we're finding square roots here, although Newton's | |
method can be used for many different kinds of functions.) | |
The only goal is for you to see how rapidly it converges, it is | |
otherwise quite useless :D.\n\n\n"; | |
print "Ok, we're trying to find the sqare root of [$square].\n\n\n"; | |
while (1) { | |
if ($guess) { | |
print "Our current guess is [$guess]. Squared, that's ". $guess*$guess .". So we're off by [". abs( $square - $guess*$guess ) ."]\n"; | |
my $next_guess = 1/2*($guess + $square/$guess); | |
print "By newton's method, our next guess is [". $next_guess . "]\n"; | |
print "Hit enter when you are ready for the next step: "; | |
<>; | |
print "\n\n"; | |
$guess = $next_guess; | |
} | |
else { | |
print "Enter your best guess for the square root! "; | |
$guess = <>; | |
chomp $guess; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment