Prev Next start_cppad.cpp

Getting Started Using CppAD with f2cad Library

Prototype
int f2cad::dscal_(integer *n, doublereal *da, doublereal *dx, integer *incx);

Description
This is a simple example using CppAD and the libf2cadCppAD.a library routine dscal to compute the function  \[
f(a) = 

\left( \begin{array}{c}
     1 \\
     2 
\end{array} \right)
\] 
We check that the derivative of this function, calculated using the CppAD, satisfies  \[
f^{(1)} (a)
=
\left( \begin{array}{c}
     1 \\
     2    
\end{array} \right)
\] 
 

// standard input output library
# include <iostream>

// f2cad set up for CppAD::AD<double>
# define F2CAD_USE_CPPAD

// prototype for dscal
# include <f2cad/dscal.hpp>

int main(void)
{	using namespace CppAD;

	// independent variables
	size_t n     = 1;                   // number of independent variables
	CppADvector< AD<double> > a(n);     // vector of independent variables
	a[0]          = 5.;                 // value of independent variables
	Independent(a);                     // declare independent variables

	// create data structure expected by dscal
	AD<double> A[1];
	A[0]         = a[0];
	integer M    = 2;
	AD<double>  F[2];
	F[0]         = 1.;
	F[1]         = 2.;
	integer Incf = 1;

	// set f = a * f 
	f2cad::dscal_(&M, A, F, &Incf );

	// dependent variables
	size_t m = 2;                       // number of dependent variables
	CppADvector< AD<double> > f(2);     // vector of dependent variables
	f[0] = F[0];                        // value of dependent variables
	f[1] = F[1];
	ADFun<double> Fun(a, f);            // declare dependent variables

	// set differential for a 
	CppADvector<double> da(n);
	CppADvector<double> df(m);
	da[0] = 1.;

	// compute differential for f
	df    = Fun.Forward(1, da);

	// print results
	std::cout << "f(a)  = a * (1, 2)^T" << std::endl;
	std::cout << "f'(a) =     (" 
                  << df[0] 
                  << ", " 
                  << df[1] 
                  << ")^T" 
                  << std::endl;

	if( df[0] != 1. || df[1] != 2. )
		return 1;  // error
	return 0;          // no error
}

Input File: get_started/cppad/run.cpp