Skip to content

[Rcpp-devel] Best Practice for Optimize Functions in RCPP

2 messages · Mark Clements, Simon Riddell

#
Alternatively, one could use the code for Brent_fmin() from the stats
library (e.g.
https://github.com/lgautier/R-3-0-branch-alt/blob/master/src/library/stats/src/optimize.c).
I have done this for the rstpm2 library
(https://github.com/mclements/rstpm2/blob/develop/src/c_optim.cpp).

This does use a C API, so I would not argue that it is "best practice".
However, using templates and function objects, this can be comparatively
general.

An inline example is below.

require(Rcpp)
require(inline)
src <- "
#include <Rcpp.h>
#include <float.h> /* DBL_EPSILON */
// From the URLs above, insert the definition for:
// double Brent_fmin(double ax, double bx, double (*f)(double, void *),
//          void *info, double tol);
//
// An example
struct Model {
    double a,b;
    double operator()(double x) {
        return pow(log(x) - a,2) + b;
    }
};
Model model = {1.0,2.0};
// template to use a function object (functor) with Brent_fmin()
template<class T>
    double Brent_fmin_functor(double x, void * par) {
    T * model = (T *) par;
    return model->operator()(x);
}
//[[Rcpp::export]]
double test_optimise() {
    return Brent_fmin(0.001,10.0,&Brent_fmin_functor<Model>,(void *)
&model,1.0e-10);
}
"
sourceCpp(code=src)
test_optimise()

Kindly, Mark.
On 12/23/2014 02:48 PM, Dirk Eddelbuettel wrote:
2 days later
#
Dear all,

Thank you for your responses. I will look into the resources and code you
have shared and hopefully I can figure something out! I appreciate your
time and help.

Simon
On Fri, Jan 2, 2015 at 12:45 PM, Mark Clements <mark.clements at ki.se> wrote: