Nasir Abbas
Nasir Abbas

Reputation: 33

Solve a double summation in R

Is there any way of solving the following sum in R:

enter image description here

Upvotes: 2

Views: 1700

Answers (2)

m0nhawk
m0nhawk

Reputation: 24168

You can calculate this without any for loops:

double_sum <- function(j) {
  sum(sapply(1:j, function(i) sum(1/i:j))^2) / j^2
}

And then calculate for each j:

> sapply(1:50, outer_sum)
 [1] 1.00000000 0.62500000 0.46296296 0.36979167 0.30866667 0.26527778 0.23279883 0.20753348 0.18729669 0.17071032
[11] 0.15686052 0.14511659 0.13502879 0.12626754 0.11858565 0.11179403 0.10574549 0.10032374 0.09543562 0.09100565
[21] 0.08697198 0.08328344 0.07989737 0.07677785 0.07389447 0.07122127 0.06873600 0.06641942 0.06425487 0.06222779
[31] 0.06032545 0.05853663 0.05685142 0.05526106 0.05375773 0.05233445 0.05098496 0.04970367 0.04848551 0.04732591
[41] 0.04622074 0.04516625 0.04415901 0.04319591 0.04227410 0.04139098 0.04054415 0.03973142 0.03895077 0.03820032

Or something strange (built upper triangle matrix for coefficient and then sum rows and results):

mat_sum <- function(j) {
  d <- outer(rep(1, j), 1:j, FUN="/")
  d[lower.tri(d)] <- 0
  sum(rowSums(d)^2) / j^2
}

And benchmarks:

> s <- 1:100
> microbenchmark::microbenchmark(for_sum=sapply(s, sumfun), double_sum=sapply(s, double_sum), mat_sum=sapply(s, mat_sum))
Unit: milliseconds
       expr      min        lq      mean    median        uq      max neval
    for_sum 9.601222 10.261159 11.996525 10.774037 11.894962 30.56077   100
 double_sum 6.075801  6.678923  8.787946  7.373223  8.697266 21.37783   100
    mat_sum 7.809572  8.770058 13.766358 10.190758 18.500802 46.18336   100

Upvotes: 4

DanY
DanY

Reputation: 6073

sumfun <- function(j) {
    res <- 0
    for(i in 1:j) {
        temp <- 0
        for(k in i:j) {
            temp <- temp + 1/(k*j)
        }
        res <- res + temp^2
    }
    return(res)
}

sapply(1:50, sumfun)


[1] 1.00000000 0.62500000 0.46296296 0.36979167 0.30866667 0.26527778 0.23279883 0.20753348 0.18729669 0.17071032 0.15686052
[12] 0.14511659 0.13502879 0.12626754 0.11858565 0.11179403 0.10574549 0.10032374 0.09543562 0.09100565 0.08697198 0.08328344
[23] 0.07989737 0.07677785 0.07389447 0.07122127 0.06873600 0.06641942 0.06425487 0.06222779 0.06032545 0.05853663 0.05685142
[34] 0.05526106 0.05375773 0.05233445 0.05098496 0.04970367 0.04848551 0.04732591 0.04622074 0.04516625 0.04415901 0.04319591
[45] 0.04227410 0.04139098 0.04054415 0.03973142 0.03895077 0.03820032

Upvotes: 2

Related Questions