Summation without loops

后端 未结 4 911
孤街浪徒
孤街浪徒 2021-01-21 15:11

I have following double summation: ∑10,i=1 ∑i,j=1 (i^5/(10+j^i))

I am quite lost with this exercise, I tried the following code but I it returns an error although giving

4条回答
  •  孤城傲影
    2021-01-21 15:39

    Make a function of the inner sum:

    f <- Vectorize(function(i) {
             j <- 1:i
             sum(i^5 / (10 + j^i))
         })
    

    By vectorizing it you can apply it to arrays, where it will operate component by component: that's what the outer sum over i says to do. Thus, the value is

    sum(f(1:10))
    

    Another solution, wasteful of RAM and a bit slower, exploits the outer product to compute all the terms of the double sum in one matrix. You have to extract the terms for which j does not exceed i:

    n <- 10
    x <- outer(1:n, 1:n, function(i,j) i^5 / (10 + j^i))
    sum(x[!upper.tri(x)])
    

    For its compactness and simplicity, though, it's a good technique to know.

提交回复
热议问题