[英]using a user defined function in Rcpp (cppFunction)
I have a user defined function in r: 我在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. 我想在使用Rcpp和cppFunction编写的c ++代码中使用此函数。 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).
即使我们不推荐使用函数,我们也展示了如何传递函数(出于明显的性能原因,从C ++调用R并非很快)。
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. 最后:您真的也想在C ++中使用
blacksch
。 All the statistical functions are available under the same names. 所有统计功能均以相同的名称提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.