【问题标题】:Turning code into a function把代码变成函数
【发布时间】:2017-07-10 19:13:24
【问题描述】:

对任何可能知道的人来说,只是一个简单的问题, 我在 R 定价选项中有以下代码:

X = 1.05
r = .85
n = 250
nsim = 2000
ctot = 0

for( i in 1:nsim){      # begining of loop
  u1=rnorm(n,0,1)
  u2=rnorm(n,0,1)
  x=u1
  y=r*u1+sqrt(1-r*r)*u2
  x=0.25/sqrt(250)*x + (0.03-0.5*0.25*0.25)/250; y= 0.25/sqrt(250)*y + (0.03-0.5*0.25*0.25)/250

  ShareA = 100*cumprod(exp(x))
  ShareB = 100*cumprod(exp(y))
  c = max(ShareA[n]-X*ShareB[n],0)
  ctot=ctot+c
}                       # end of loop
  c=ctot/nsim   
  c=c*exp(-0.03)
c

我的问题是我怎样才能把它变成一个函数,我可以将相关性 r 更改为我喜欢的任何东西? 希望这是有道理的……本质上问题是把这段代码变成一个函数。 谢谢 感谢所有建议。

【问题讨论】:

  • 如果你在stackoverflow上问这个问题会更好
  • 请学习An Introduction to R.

标签: r normal-distribution simulation function


【解决方案1】:

将此调用选项转换为接受相关性作为参数的函数:

callOptionEval<-function(r=0.85){
  X = 1.05 ; n = 250; nsim = 2000; ctot = 0;

  for( i in 1:nsim){ # begining of loop 
    u1=rnorm(n,0,1); 
    u2=rnorm(n,0,1);
    x=u1; 
    y=r*u1+sqrt(1-r*r)*u2; 
    x=0.25/sqrt(250)*x + (0.03-0.5*0.25*0.25)/250; 
    y= 0.25/sqrt(250)*y + (0.03-0.5*0.25*0.25)/250;

    ShareA = 100*cumprod(exp(x));
    ShareB = 100*cumprod(exp(y));
    c = max(ShareA[n]-X*ShareB[n],0);
    ctot=ctot+c;

  } # end of loop c=ctot/nsim
  c=c*exp(-0.03); 
  return(c)
} 
callOptionEval(0.85)# gives 0 
callOptionEval(0.5)# gives 12.45512

请注意,这段代码并没有做函数应该检查输入是否在 $(-1, 1)$ 等之间的有用的东西。这对当前用户来说更像是一个方便的函数。

【讨论】:

  • 非常感谢您,是的,您是对的,它更多的是方便因素。再次感谢您
  • 如果此答案解决了您的问题,将问题标记为已接受将关闭问题。
【解决方案2】:

mycorr &lt;- function(x, r, n, nsim, ctot) { Your remaining lines and loops here }

将其用作 mycorr(X = 1.05, r = .85, n = 250, nsim = 2000, ctot = 0)

【讨论】:

  • 很高兴你这样做了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多