Skip to content

Instantly share code, notes, and snippets.

@msouth
Created July 29, 2019 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msouth/8e419fba776af300b2636901bf51b2f1 to your computer and use it in GitHub Desktop.
Save msouth/8e419fba776af300b2636901bf51b2f1 to your computer and use it in GitHub Desktop.
Watch Newton's method converge
my $square = shift or die "Usage: $0 3 [where 3 is the number you want to find the square root of]";
my $guess;
print
"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