Code:
our $start = -50; #
our $count = 100; # Range to test for switch on x-axis
our $buffer;
sub f { # Your f(x). ** = ^
my $x = shift;
return $x**3+2*$x-1;
}
sub abl { # Derivation of f(x). ** = ^
my $x = shift;
return 3*$x**2+2;
}
print "\n".("\t"x3)."### Newton's method by Bonkers ### \n\n";
print "\n\tSearching for switch on x-axis (From ".$start." to ".$count.")...\n\n";
sub isPos { # Is the value positive?
my $cc = shift;
#if ($cc > 0) { return 1 } else { return 0 };
return $cc > 0;
}
sub output { # To format Output
my $work = shift;
if (length($work) > 9) { return substr($work, 0,10); } else { return $work.(" "x(10-length($work))) }
}
for (my $i = $start; $i < ($start+$count); $i++) {
$buffer = f($i);
my $sec = f($i+1);
if (isPos($buffer) != isPos($sec)) {$buffer = $i - 1; $i = ($start+$count); }
}
print "\tDone. Selected Value to start with: xn = ".$buffer."\n\n";
our $maximum = $ARGV[0];
if ($maximum != 0) { if ($maximum == "") { $maximum = 100; }}
print "\tMaximum steps, taken from first Argument (Default is 0) : ".$maximum."\n\tUse 0 for Auto-Stop.\n\n\nPress Enter to start. "; <STDIN>;
print "\n\n\t ".("_"x62)."\n\t| Xn | f(xn) | f'(xn) | 1-xn |"."\n\t|".("-"x62)."\n";
print "\t| ".output($buffer)." | ".output(f($buffer))." | ".output(abl($buffer))." | ".output(1-(f($buffer)/abl($buffer)))." | \n";
for (my $counter = -1; $counter < $maximum;) {
$buffer = 1-(f($buffer)/abl($buffer));
print "\t| ".output($buffer)." | ".output(f($buffer))." | ".output(abl($buffer))." | ".output(1-(f($buffer)/abl($buffer)))." | \n";
if ($maximum != 0) { $counter++; } else { if ($buffer eq (1-(f($buffer)/abl($buffer)))) { $maximum = 1; $counter = 1;} }
}
print "\t-".("-"x62).("\n"x3)."\t\t Done :)\n\n";