Code:
#!/usr/bin/perl
use strict;
use warnings;
sub print_polynom
{
my %poly = %{$_[0]};
my %sign = (-1 => "-", 1 => "+");
my $i = 0;
foreach my $key (reverse sort keys %poly)
{
my $val = $poly{$key};
next if $val == 0;
print " " . $sign{$val / abs $val} . " " if $i++ != 0 || $val < 0;
print abs($val) if $key == 0;
print abs($val) . "*x" if $key == 1;
print abs($val) . "*x^$key" if $key != 0 && $key != 1;
}
print "\n";
}
sub calc_derivate
{
my %poly = %{$_[0]};
foreach my $key (keys %poly)
{
# Verwendete Ableitungsregeln:
# ----------------------------
# f(x) = a * x^n --> f'(x) = an * x^(n-1)
# f(x) = g(x) + h(x) --> f'(x) = g'(x) + h'(x)
$_{$key - 1} = $key * $poly{$key};
}
return %_;
}
sub eval_polynom
{
my %poly = %{$_[0]};
my $x = $_[1];
$_ = 0;
foreach my $key (keys %poly)
{
$_ += $poly{$key} * ($x ** $key);
}
return $_;
}
my %poly = (
# f(x) = 1*x^3 + 2*x - 1
3 => 1,
1 => 2,
0 => -1
# --> f'(x) = 3*x^2 + 2
);
# Polynom ausgeben...
print "f(x) = ";
&print_polynom(\%poly);
# Ableitung berechnen und ausgeben...
my %deri = &calc_derivate(\%poly);
print "f'(x) = ";
&print_polynom(\%deri);
# f(0) berechnen und ausgeben...
print "f(0) = ";
print &eval_polynom(\%poly, 0);
print "\n";