Prev Next a_fun_forward_xam.pm Headings

@(@\newcommand{\B}[1]{ {\bf #1} } \newcommand{\R}[1]{ {\rm #1} }@)@
Perl: Forward Mode AD: Example and Test
package a_fun_forward_xam;
sub a_fun_forward_xam() {
     # check for standard perl programming conventions
     use strict;
     use warnings;
     #
     # load the Cppad Swig library
     use pm_cppad;
     #
     # initilaize return variable
     my $ok = 1;
     # ---------------------------------------------------------------------
     # number of dependent and independent variables
     my $n_dep = 1;
     my $n_ind = 2;
     #
     # create the independent variables ax
     my $xp = new pm_cppad::vec_double($n_ind);
     for(my $i = 0; $i < $n_ind ; $i++) {
          $xp->set($i, $i + 1.0);
     }
     my $ax = pm_cppad::independent($xp);
     #
     # create dependent varialbes ay with ay0 = ax0 * ax1
     my $ax0 = $ax->get(0);
     my $ax1 = $ax->get(1);
     my $ay = new pm_cppad::vec_a_double($n_dep);
     $ay->set(0, $ax0 * $ax1);
     #
     # define af corresponding to f(x) = x0 * x1
     my $af = new pm_cppad::a_fun($ax, $ay);
     #
     # define X(t) = (3 + t, 2 + t)
     # it follows that Y(t) = f(X(t)) = (3 + t) * (2 + t)
     #
     # Y(0) = 6 and p ! = 1
     my $p = 0;
     $xp->set(0, 3.0);
     $xp->set(1, 2.0);
     my $yp = $af->forward($p, $xp);
     $ok = $ok && $yp->get(0) == 6.0;
     #
     # first order Taylor coefficients for X(t)
     $p = 1;
     $xp->set(0, 1.0);
     $xp->set(1, 1.0);
     #
     # first order Taylor coefficient for Y(t)
     # Y'(0) = 3 + 2 = 5 and p ! = 1
     $yp = $af->forward($p, $xp);
     $ok = $ok && $yp->get(0) == 5.0;
     #
     # second order Taylor coefficients for X(t)
     $p = 2;
     $xp->set(0, 0.0);
     $xp->set(1, 0.0);
     #
     # second order Taylor coefficient for Y(t)
     # Y''(0) = 2.0 and p ! = 2
     $yp = $af->forward($p, $xp);
     $ok = $ok && $yp->get(0) == 1.0;
     #
     return( $ok );
}

Input File: build/lib/example/perl/a_fun_forward_xam.pm