Home > other >  How to fix this r code to get the correct values for 1 to 100?
How to fix this r code to get the correct values for 1 to 100?

Time:01-24

In the following code, when I try N = 100, I get the answer as 5.352954 but when I enter N=1:100 to get a table for all the 100 values, the 100th value shown is 1.123200e-27. Why the discrepancy? I was hoping for the table to show the 100th value as 5.352954. Help with fixing this code would be appreciated. Thank you very much.

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)

CodePudding user response:

This is because function Task_binom is not vectorized. You can do the following:

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

CodePudding user response:

Two quick points to check which might solve your problem:

  1. Your 'for' loop is already specified as 1:N so if you make N = 1:100 then your loop is trying to do 1:1:100 which will end badly.

  2. There are a number of places where you use N as a single number in your function (e.g. calculations of 'h', 'helper' and 'p_0') which wouldn't work with N = 1:100.

  •  Tags:  
  • r
  • Related