Skip to content
Prev 139928 / 398502 Next

How to remove double loop?

On Thu, 20 Mar 2008, Alberto Monteiro wrote:
Unfortunately, neither of these loop removals gives the same answers as the 
original code :-( [Hence the request for reproducible code].  Try:
TreeMy(K=0.5)

What does work though is the following:

TreeMy <- 
function(S=50,K=50,sigma=0.4,r=0.1,Time=1,n=3){
dtime <- Time/n
u <- exp(sigma*sqrt(dtime))
d <- 1/u
p <- (exp(r*dtime)-d)/(u-d)
a <- exp(-r*dtime)

OVal <- matrix(0, n+1, n+1)

Val <- outer(0:n, 0:n, function(i, j) ifelse(i <= j, u^i*d^(j-i), 0))

OVal[, n+1] <- pmax(Val[, n+1]-K, 0)

for (i in n:1) {
    OVal[1:i, i] <-  colSums(matrix(a*c((1 - p), p)*
    OVal[, i + 1][rep(1:2, i) + rep(0:(i - 1), each=2)], ncol=i))
}

list("Stock Price"=Val, "Option Price"=OVal)
}

Here the first loop is removed with a simple pmax() (the 'vector' form of 
max()).  The second loop uses the trick of expanding the column operations 
into a vector using recycling then restructuring them back into a matrix.  
This provides a significant speed improvement.

HTH
Ray Brownrigg