[Rcpp-devel] Best Practice for Optimize Functions in RCPP
Mark Clements
mark.clements at ki.se
Fri Jan 2 21:45:08 CET 2015
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:
> On 23 December 2014 at 08:21, Hao Ye wrote:
> | There are also some minima-finding functions in GSL that you may want to look
> | into. The source for RcppGSL might help with a fully c++ version.
>
> Yes. And there are a bazillion optimisation packages on CRAN:
> http://cran.r-project.org/web/views/Optimization.html
> Several of these are already used in a Rcpp context.
>
> Also, I once needed something similar to what Avi described here, and just 'ripped
> out' a simple one-dim optimizer (to compute implied vols for a lot of option
> price series quickly, so I took the optmizier from QuantLib) -- and blogged
> about it: http://dirk.eddelbuettel.com/blog/2012/10/25/ This isn't all that
> hard, and we can probably help Simon here.
>
> A different (and harder to grok at first) take is in RcppDE where I reworked
> the DEoptim optimization package (and "ported" from C to C++ wit RcppArmadillo)
> and allowed use of user-supplied functions to optimize for -- given as C++
> functions. This is likely to confuse Simon now, but some other people have
> used this scheme.
>
> Dirk
>
More information about the Rcpp-devel
mailing list