user1780302
user1780302

Reputation: 11

R sum over infinite series loop?

I have this:

time=1:200
m=1:1000

sum[i]= sum(1/(1+2*m)^2)*exp( (-kappa*(1+2*m)^2 * pi^2 * time[i])/(z1^2))

I need to find the sum of the expression above for m=1:1000 and time=1:200

I have tried many variety of loop and cannot make it stick. I am even having trouble expressing this here....

Upvotes: 0

Views: 4055

Answers (3)

RJ-
RJ-

Reputation: 3037

Another way to do this:

output <- expand.grid(time = 1:200, m =1:1000)
output[,"sum"] <- with(output, sum(1/(1+2*m)^2)*exp( (-kappa*(1+2*m)^2 * pi^2 * time)/(z1^2)))

Upvotes: 0

Ryan
Ryan

Reputation: 121

Maybe this will work:

sum<-0    
time<-0

for(i in 1:200){
  time<-time+1
  m<-0

  for(j in 1:1000){
    m<-m+1
    sum<-sum+(1/(1+2*m)^2)*exp((-kappa*(1+2*m)^2*pi^2*time)/(z1^2))
    }
}

The loops should repeat the equation 200,000 times, once with each combination of m and time. At the end, sum should be the sum of all these equations. However, I don't know what kappa and z1 are, so my script may need some tweaking.

Upvotes: 0

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

This command will return a matrix:

time <- 1:200
m <- 1:1000

sapply(time,
       function(time) sum(1/(1+2*m)^2)*exp((-kappa*(1+2*m)^2*pi^2*time)/(z1^2)))

In the matrix you will find the result for all combinations. The rows indicate the values of m, the columns indicate the values of time.

Upvotes: 1

Related Questions