Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to calculate the total of the sequence

Tags:

r

I am trying to calculate the sum of this sequence in R.

The sequence will have two Inputs (1 and 11) in the below case,

1 + (1 * 2/3 ) + (1 * 2/3 * 4/5) + ( 1 * 2/3 * 4/5 * 6/7) + ....................(1 *......10/11)

I think, defining my own is the way to go here.

like image 630
Siddharth Thanga Mariappan Avatar asked Jan 30 '23 08:01

Siddharth Thanga Mariappan


2 Answers

You could try just using old-fashioned loops here:

sum <- 0
num_terms <- 6
for (i in 1:num_terms) {
    y <- 1
    if (i > 1) {
        for (j in 1:(i-1)) {
            y <- y * (j*2 / (j*2 + 1))
        }
    }
    sum <- sum + y
}

You can set num_terms to any value you want, from 1 to a higher value. In this case, I use 6 terms because this is the requested number of terms in your question.

Someone will probably come along and reduce the entire code snippet above to one line, but in my mind an explicit loop is justified here.

Here is a link to a demo which prints out the values being used in each of the terms, for verification purposes:

Demo

like image 175
Tim Biegeleisen Avatar answered Feb 01 '23 08:02

Tim Biegeleisen


My approach:

# input
start <- 1
n <- 5 # number of terms

end <- start + n*2

result <- start
to_add <- start

for (i in (start + 1):(end-1)) {
  to_add <- to_add * (i / (i + 1))
  result <- result + to_add
}

which gives:

> result
[1] 4.039755
like image 29
brettljausn Avatar answered Feb 01 '23 09:02

brettljausn