简体   繁体   中英

using a user defined function in Rcpp (cppFunction)

I have a user defined function in r:

blacksch<-function(s_0,k,sigma,r,t)
{
  d1=(log(s_0/k) + (r + (sigma^2)/2)*(t))/(sigma*sqrt(t))
  d2=(log(s_0/k) + (r - (sigma^2)/2)*(t))/(sigma*sqrt(t))

  p=(pnorm(-d2)*k*exp(-r*t))-pnorm(-d1)*s_0
}

And I would like to use this function in c++ code that I have written using Rcpp and cppFunction. I have been through the documentation and examples a few times, but have not been successful.

bs_martin<-cppFunction('NumericMatrix compMartin (NumericMatrix st, NumericMatrix dv, double s_0, double k, 
                       double t, double sigma, double r, int steps, int paths, Function blacksch(fun)) {

                       // Ensure RNG scope set
                       RNGScope scope;


        int min_bs_step=0;
        double minbsvalue=0;
        vector<double> u[0]=100.0;
        for(int i=1;i<=paths; i++)
        {
          min_bs_step=0;
          for(int j=1;j<=steps;j++)
          {
            if (dv[i,j]>0 && min_bs_step==0)
            {
                min_bs_step=i;
                minbsvalue=blacksch(s_0,k,sigma,r,t);
            }
            else if (min_bs_step!=0)
            {
                dv[i,j]=1 - minbsvalue;
            }
          }

        }
      return dv;
                       }')

I would suggest the following:

  • Study our documentation and examples. We show how to pass functions around too, even if we do not recommend it (for obvious performance reason, calling R from C++ ain't speedy).

  • If you somewhat complex example does not work, try a smaller one. At the end of the day you may just want a tester which receives two numbers and passes those to a supplied function.

  • And lastly: You really want blacksch in C++ too. All the statistical functions are available under the same names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM