Skip to content
Prev 248157 / 398506 Next

Vectorization

On Sun, Jan 23, 2011 at 07:29:16PM -0800, eric wrote:
Hello.

The cycle computes a cumulative product. The initialization may
be add as a common multiplier. So, z in the following should be equal
to x up to the machine rounding error.

  y <- c(
    0.003990746, -0.037664639,  0.005397999,  0.010415496,  0.003500676,
    0.001691775,  0.008170774,  0.011961998, -0.016879531,  0.007284486,
   -0.015083581, -0.006645958, -0.013153103,  0.028148639, -0.005724317,
   -0.027408025,  0.014767422, -0.001619691,  0.018334730, -0.009747171)
 
  x <- numeric(length(y))
  for (i in 1:length(y)) {
      x[i] <- ifelse(i==1, 10000*(1+y[i]), (1+y[i])*x[i-1])
  }
 
  z <- 10000*cumprod(1 + y)
 
  max(abs(x - z))
  # [1] 1.818989e-12

Petr Savicky.