如何修复此r代码以获得1到100的正确值?

velaa5lx  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(140)

在下面的代码中,当我尝试N = 100时,我得到的答案是5.352954,但是当我输入N=1:100来获取所有100个值的表格时,显示的第100个值是1.123200e-27。为什么会有差异?我希望表格显示的第100个值是5.352954。如果能帮助修复这个代码,我将不胜感激。非常感谢。

Task_binom <- function(N, Time, sigma, rho, St, K, put = T){
  
  h <- Time/N
  rf <- rho*h
  sd <- sigma*sqrt(h)
  u <- exp(sd)
  d <- 1/u
  pi <- (1+rf-d)/(u-d)
  
  sum <- 0
  
  if(put == T){
    
    for (i in 1:N) {
      helper <- choose(N,i)*pi^i*(1-pi)^(N-i)*max(K - St*u^i*d^(N-i),0)
      sum <- helper + sum
    }
    p_0 <- 1/(1+rf)^N * sum
    return(p_0)}
  else{
    for (i in 1:N) {
      helper <-choose(N,i)*pi^i*(1-pi)^(N-i)*max(St*u^i*d^(N-i) - K,0)
      sum <- helper + sum
    }
    p_0 <- 1/(1+rf)^N * sum
    return(p_0)
  }
}

Task_binom(100,0.0833,0.3299,0.0472,134.51,134.51,put=F)
Task_binom(1:100,0.0833,0.3299,0.0472,134.51,134.51,put=F)
agxfikkp

agxfikkp1#

这是因为函数Task_binom没有矢量化。您可以执行以下操作:

sapply(1:100,Task_binom,0.0833,0.3299,0.0472,134.51,134.51,put=F)

  [1] 6.649708 4.784997 5.798963 5.059390 5.624142 5.158321 5.549569 5.209064 5.508332
 [10] 5.239888 5.482184 5.260587 5.464130 5.275442 5.450917 5.286621 5.440830 5.295337
 [19] 5.432878 5.302323 5.426447 5.308048 5.421139 5.312824 5.416684 5.316870 5.412892
 [28] 5.320340 5.409624 5.323350 5.406780 5.325986 5.404282 5.328313 5.402070 5.330382
 [37] 5.400097 5.332234 5.398328 5.333902 5.396732 5.335411 5.395285 5.336783 5.393966
 [46] 5.338037 5.392760 5.339186 5.391653 5.340244 5.390633 5.341221 5.389690 5.342125
 [55] 5.388815 5.342965 5.388003 5.343747 5.387245 5.344477 5.386537 5.345160 5.385874
 [64] 5.345801 5.385252 5.346402 5.384668 5.346969 5.384117 5.347503 5.383597 5.348007
 [73] 5.383106 5.348485 5.382641 5.348937 5.382200 5.349366 5.381782 5.349774 5.381384
 [82] 5.350161 5.381005 5.350531 5.380645 5.350883 5.380301 5.351219 5.379972 5.351540
 [91] 5.379658 5.351848 5.379357 5.352142 5.379069 5.352424 5.378793 5.352695 5.378529
[100] 5.352954
3zwtqj6y

3zwtqj6y2#

有两个要点可以快速检查,以解决您的问题:
1.你的“for”循环已经被指定为1:N,所以如果你让N = 1:100,那么你的循环试图做1:1:100,这将结束得很糟糕。
1.在很多情况下,您在函数中使用N作为单个数字(例如,计算'h'、'helper'和'p_0'),这在N = 1:100时不起作用。

相关问题