Function to calculate the complete sequence

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

The sequence will have two inputs (1 and 11) in the following case,

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

I think the definition of my own is the way here.

+4
source share
4 answers

You can 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_termsany value you want, from 1to a higher value. In this case, I use terms 6because this is the requested number of terms in your question.

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

, , , :

+4

:

# 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
}

:

> result
[1] 4.039755
+2

Another alternative to the R base that uses cumprodto generate internal terms is

sum(cumprod(c(1, seq(2, 10, 2)) / c(1, seq(3, 11, 2))))
[1] 3.4329

Here it c(1, seq(2, 10, 2)) / c(1, seq(3, 11, 2))generates the sequence 1, 2/3, 4/5, 6/7, 8/9, 10/11 and cumprodtakes the cumulative product. This result is cumulative with sum. The result obtained is identical to that returned in the accepted answer.

+1
source

you can try:

library(tidyverse)
Result <- tibble(a=seq(1, 11, 2)) %>%
  mutate(b=lag(a, default = 0)+1) %>% 
  mutate(Prod=cumprod(b)/cumprod(a)) %>%  
  mutate(Sum=cumsum(Prod)) 
Result 
  # A tibble: 6 x 4
      a     b      Prod      Sum
  <dbl> <dbl>     <dbl>    <dbl>
1     1     1 1.0000000 1.000000
2     3     2 0.6666667 1.666667
3     5     4 0.5333333 2.200000
4     7     6 0.4571429 2.657143
5     9     8 0.4063492 3.063492
6    11    10 0.3694084 3.432900

# and some graphical analysis
Result %>% 
  ggplot(aes(as.factor(a), Prod, group=1)) + 
    geom_col(aes(as.factor(a), Sum), alpha=0.4)+ 
    geom_point() + 
    geom_line() 

enter image description here

+1
source

Source: https://habr.com/ru/post/1688073/


All Articles