Skip to content

Instantly share code, notes, and snippets.

@tomcha tomcha/newton.pl
Created Apr 13, 2019

Embed
What would you like to do?
ニュートン法
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use DDP { deparse => 1 };
print "求めたい平方根を入力>>";
chomp(my $root_num = <STDIN>);
my $x= 3;
my $delta_limit = 0.0000001;
my $new_x = calc_point($x);
while ($x - $new_x > $delta_limit){
$x = $new_x;
$new_x = calc_point($x);
}
say $new_x;
sub calc_point{
my $i = shift;
my $mo = 2 * $i;
my $chi = ($i ** 2 - $root_num);
my $result = $i - $chi / $mo;
return $result;
}
__END__
memo
f(x) = x^2 - $root_num;
f(x) = 0;
f'(x) = 2x;
f'(x0) = 2x0;
f'(x0) = f(x0) / x0 - x1
2x0 = f(x0) / x0 - x1
f(x0) = x0^2 - root_num
2x0 = x0^2 - root_num / x0 - x1
x0 - x1 = x0^2 - root_num / 2x0
- x1 = x0^2 - root_num / 2x0 - x0
x1 = - (x0^2 - root_num / 2x0) + x0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.