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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With