简体   繁体   中英

Function to calculate the total of the sequence

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:

Demo

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

Another base R alternative using cumprod to generate the inner terms is

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

Here, 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 cumprod takes the cumulative product. This result is summed with sum . The returned result is identical to the one in the accepted answer.

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() 

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM