Ewa Michalska
Ewa Michalska

Reputation: 95

Solving double summation in R studio without loops

Double summation Tried solve this double summation in R ( ∑10i=1∑5j=1(i^5(10+j^i) ) without using loops

in this way, but when solving it manually in hand I got a different answer - is this the correct way of solving such a problem? Here I get the solution: 260.1827

 i <- seq(1, 10, 1) 
 j <- seq(1, 5, 1)
 denominators <- 10+j^i 
 fractions <- (i^5)/denominators
 sum(fractions)

Possible solution

Upvotes: 0

Views: 1151

Answers (3)

Ricardo Semi&#227;o
Ricardo Semi&#227;o

Reputation: 4456

Using for loops:

sum = 0
for(i in 1:10){
  for(j in 1:5){
    sum = sum + i^5/(10+j^i)
  }
}

Result:

> sum
[1] 20845.76

Without loops:

i = rep(1:10, each=5)
j = rep(1:5, 10)

This way i and j looks like:

> i
 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6 6 6 6 7 7 7 7 7 8 8 8 8 8 9 9 9 9 9 10 10 10 10 10

> j
 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1  2  3  4  5

So every 5 j's turns i up by one, then resets j.

sum(i^5/(10+j^i))

(Same result)

Upvotes: 3

Jonas
Jonas

Reputation: 1810

First, define the inner sum as a function of i:

innerSum <- function(i) { 
  #The inner sum is a function of i, looping over each j from 1 to 5
  i^5 / (10+(1:5)^i)
}

Now, for every i from 1 to 10 you have to calculate this function and then add everything together. This can be done via sapply. This is a function that iterates over a collection-like datastructure (in our case the vector with the numbers for i), applies a function to every element and returns a vector with the function-results. The final step is to add everything together with sum:

sum(sapply(1:10, function(i) innerSum(i))) #returns 20845.76

Moreover, you can save some syntax. You could write

sum(sapply(1:10, innerSum)) #returns 20845.76

This is possible because the function innerSum only takes one argument and it is "clear for R", what to do. For more details, have a look at the documentation of sapply via calling ?sapply in R-Studio.

Update: With sapply you are using an implicit loop. So if you have to avoid loops, please mark Ricardos new answer as the accepted one. To be fair, mine is not correct therefore.

Upvotes: 1

John Coleman
John Coleman

Reputation: 51998

You can use expand.grid and apply:

> sum(apply(expand.grid(i,j),1,function(v)v[1]^5/(10+v[2]^v[1])))
[1] 20845.76

Upvotes: 2

Related Questions