Antonio Coppola edited C++ Functions.tex  over 9 years ago

Commit id: 9eb083607677f297c7cc8c372e5b172be67b78d4

deletions | additions      

       

The package supports the implementation of the objective and gradient functions in C++, which may yield significant speed improvements over the respective R implementations. The optimization routine's API accepts both R function objects and external pointers to compiled C++ functions. To perform optimization on the Rosenbrock function, we begin by defining the C++ implementations of the objective and of the gradient as character strings:  \lstset{language=R}  \begin{lstlisting}  objective.include <- 'Rcpp::NumericVector rosenbrock(SEXP xs) {   Rcpp::NumericVector x(xs);  double x1 = x[0];  double x2 = x[1];  double sum = 100 * (x2 - x1 * x1) * (x2 - x1 * x1) + (1 - x1) * (1 - x1);  Rcpp::NumericVector out(1);  out[0] = sum;  return(out);  }  '  gradient.include <- 'Rcpp::NumericVector rosengrad(SEXP xs) {  Rcpp::NumericVector x(xs);  double x1 = x[0];  double x2 = x[1];  double g1 = -400 * x1 * (x2 - x1 * x1) - 2 * (1 - x1);  double g2 = 200 * (x2 - x1 * x1);  Rcpp::NumericVector out(2);  out[0] = g1;  out[1] = g2;  return(out);  }'  \end{lstlisting}